是否可以查看 HttpClient 的 org.apache.http.conn.EofSensorInputStream?

Is it possible to peek HttpClient's org.apache.http.conn.EofSensorInputStream?

我正在尝试查看来自 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(); }

它returns的输入流是org.apache.http.conn.EofSensorInputStream

类型

我们的用例是这样的,我们需要在输入流的第一个(最多 64k)字节处 "peek"。我使用此处描述的算法 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) 我会得到所有内容。

参见InputStream#read(byte[] b,int off,int len)合同:

Reads up to len bytes of data from the input stream into an array of bytes. An attempt is made to read as many as len bytes, but a smaller number may be read. The number of bytes actually read is returned as an integer

不要使用此方法,而是使用 IOUtils.read,它会一直读取,直到获得循环中请求的字节数。