使用htpp客户端时流关闭

时间:2015-08-07 17:18:08

标签: java httpclient

当使用httpclient获取响应时,我在网上收到错误     out.write(EntityUtils.toString(resEntity)); //它是java代码中的第70行

为什么会这样?

    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();

错误是

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)     at java.util.zip.GZIPInputStream.ensureOpen(GZIPInputStream.java:61)
2015/08/07 13:03:12,887 ERROR [stderr] (Thread-101)     at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:112)
2015/08/07 13:03:12,887 ERROR [stderr] (Thread-101)     at org.apache.http.client.entity.LazyDecompressingInputStream.read(LazyDecompressingInputStream.java:74)
2015/08/07 13:03:12,887 ERROR [stderr] (Thread-101)     at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283)
2015/08/07 13:03:12,887 ERROR [stderr] (Thread-101)     at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)
2015/08/07 13:03:12,887 ERROR [stderr] (Thread-101)     at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
2015/08/07 13:03:12,887 ERROR [stderr] (Thread-101)     at java.io.InputStreamReader.read(InputStreamReader.java:184)
2015/08/07 13:03:12,888 ERROR [stderr] (Thread-101)     at java.io.Reader.read(Reader.java:140)
2015/08/07 13:03:12,888 ERROR [stderr] (Thread-101)     at org.apache.http.util.EntityUtils.toString(EntityUtils.java:244)
2015/08/07 13:03:12,888 ERROR [stderr] (Thread-101)     at org.apache.http.util.EntityUtils.toString(EntityUtils.java:288)
2015/08/07 13:03:12,888 ERROR [stderr] (Thread-101)     at mainThread.Search.doRequest(Search.java:70)
2015/08/07 13:03:12,888 ERROR [stderr] (Thread-101)     at mainThread.Search.search(Search.java:29)
...

同时,来自请求的响应已在线

成功收到
System.out.println(EntityUtils.toString(resEntity));

1 个答案:

答案 0 :(得分:9)

您无法两次读取响应流,这是您通过两次有效地调用EntityUtils.toString(resEntity)所做的事情。

System.out.println(EntityUtils.toString(resEntity)); // once
// ...
out.write(EntityUtils.toString(resEntity)); // twice

当你第二次到达时,响应流没有更多的数据可供阅读。

在这种情况下,只需确保通过将结果字符串分配给变量来读取响应流一次。然后,您可以根据需要安全地使用该字符串变量。

String resEntityToString = EntityUtils.toString(resEntity);
System.out.println(resEntityToString);
// ...
out.write(resEntityToString);