【发布时间】:2017-11-12 10:33:02
【问题描述】:
我正在尝试查看来自 HttpClient 的输入流内容,最多 64k 字节。
流来自一个 HttpGet,没什么特别的:
HttpGet requestGet = new HttpGet(encodedUrl);
HttpResponse httpResponse = httpClient.execute(requestGet);
int status = httpResponse.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK) {
return httpResponse.getEntity().getContent();
}
它返回的输入流的类型是org.apache.http.conn.EofSensorInputStream
我们的用例是这样的,我们需要“窥视”输入流的第一个(最多 64k)字节。我使用这里描述的算法How do I peek at the first two bytes in an InputStream?
PushbackInputStream pis = new PushbackInputStream(inputStream, DEFAULT_PEEK_BUFFER_SIZE);
byte [] peekBytes = new byte[DEFAULT_PEEK_BUFFER_SIZE];
int read = pis.read(peekBytes);
if (read < DEFAULT_PEEK_BUFFER_SIZE) {
byte[] trimmed = new byte[read];
System.arraycopy(peekBytes, 0, trimmed, 0, read);
peekBytes = trimmed;
}
pis.unread(peekBytes);
当我使用 ByteArrayInputStream 时,这没有问题。
问题:使用org.apache.http.conn.EofSensorInputStream 时,我只在流的开头得到少量字节。通常大约 400 字节。当我预计最多 64k 字节时。
我还尝试使用BufferedInputStream 读取前64k 字节,然后调用.reset(),但这也不起作用。同样的问题。
为什么会这样?我不认为有任何东西会关闭流,因为如果你打电话给IOUtils.toString(inputStream),我会得到所有的内容。
【问题讨论】:
标签: java httpclient inputstream