java - Stream closed when using htpp client -
when using httpclient response error on line out.write(entityutils.tostring(resentity));
// line 70 in java code
why happens?
closeablehttpclient httpclient = httpclients.custom().setuseragent("mozilla/5.0 (windows nt 6.3; rv:36.0) gecko/20100101 firefox/36.0").build(); httpresponse response = httpclient.execute(new httpget(searchlink.tostring())); httpentity resentity = response.getentity(); system.out.println(entityutils.tostring(resentity)); printwriter out = new printwriter(new file("searchresult.xml")); out.write(entityutils.tostring(resentity)); out.flush(); out.close(); httpclient.close();
the error is
2015/08/07 13:03:12,887 error [stderr] (thread-101) java.io.ioexception: stream closed 2015/08/07 13:03:12,887 error [stderr] (thread-101) @ java.util.zip.gzipinputstream.ensureopen(gzipinputstream.java:61) 2015/08/07 13:03:12,887 error [stderr] (thread-101) @ java.util.zip.gzipinputstream.read(gzipinputstream.java:112) 2015/08/07 13:03:12,887 error [stderr] (thread-101) @ org.apache.http.client.entity.lazydecompressinginputstream.read(lazydecompressinginputstream.java:74) 2015/08/07 13:03:12,887 error [stderr] (thread-101) @ sun.nio.cs.streamdecoder.readbytes(streamdecoder.java:283) 2015/08/07 13:03:12,887 error [stderr] (thread-101) @ sun.nio.cs.streamdecoder.implread(streamdecoder.java:325) 2015/08/07 13:03:12,887 error [stderr] (thread-101) @ sun.nio.cs.streamdecoder.read(streamdecoder.java:177) 2015/08/07 13:03:12,887 error [stderr] (thread-101) @ java.io.inputstreamreader.read(inputstreamreader.java:184) 2015/08/07 13:03:12,888 error [stderr] (thread-101) @ java.io.reader.read(reader.java:140) 2015/08/07 13:03:12,888 error [stderr] (thread-101) @ org.apache.http.util.entityutils.tostring(entityutils.java:244) 2015/08/07 13:03:12,888 error [stderr] (thread-101) @ org.apache.http.util.entityutils.tostring(entityutils.java:288) 2015/08/07 13:03:12,888 error [stderr] (thread-101) @ mainthread.search.dorequest(search.java:70) 2015/08/07 13:03:12,888 error [stderr] (thread-101) @ mainthread.search.search(search.java:29) ...
at same time response request recieved on line
system.out.println(entityutils.tostring(resentity));
you can't read response stream twice, doing invoking entityutils.tostring(resentity)
twice.
system.out.println(entityutils.tostring(resentity)); // once // ... out.write(entityutils.tostring(resentity)); // twice
by time 2nd time, response stream has no more data read.
in case, make sure read response stream once assigning resulting string variable. can safely use string variable many times like.
string resentitytostring = entityutils.tostring(resentity); system.out.println(resentitytostring); // ... out.write(resentitytostring);
Comments
Post a Comment