CloseableHttpClient 读取响应 Stream closed
org.apache.http.impl.client.CloseableHttpClient 读取响应 Stream closed
现场
在使用HttpClient的时候,读取响应的时候,总提示流被关闭。
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpResponse httpResponse = execute(httpClient, httpPost);
try {
EntityUtils.toByteArray(httpResponse.getEntity());
EntityUtils.toString(httpResponse.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
错误
发现报错,错误如下:
java.io.IOException: Stream closed
at java.util.zip.GZIPInputStream.ensureOpen(GZIPInputStream.java:62)
at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:113)
at org.apache.http.client.entity.LazyDecompressingInputStream.read(LazyDecompressingInputStream.java:70)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.Reader.read(Reader.java:140)
at org.apache.http.util.EntityUtils.toString(EntityUtils.java:227)
问题原因
既然输出流被关闭,肯定是读完之后被恶意关闭了。找到源码。

出现这种问题,是因为EntityUtils操作了2次,toByteArray读完了,直接关闭了输出流。toString也是,读完了直接关闭。


浙公网安备 33010602011771号