我正在将一些代码从 Http Client 3.x 库转换为 Http Components 4.x 库。旧代码包含一个检查,以确保响应不超过特定大小。这在 Http Client 3.x 中相当容易做到,因为您可以使用 getResponseBodyAsStream() 方法从响应中取回流并确定何时超出大小。我在 Http Components 中找不到类似的方法。
这是旧代码作为我正在尝试做的示例:
private static final long RESPONSE_SIZE_LIMIT = 1024 * 1024 * 10;
private static final int READ_BUFFER_SIZE = 16384;
private static ByteArrayOutputStream readResponseBody(HttpMethodBase method)
throws IOException {
int len;
byte buff[] = new byte[READ_BUFFER_SIZE];
ByteArrayOutputStream out = null;
InputStream in = null;
long byteCount = 0;
in = method.getResponseBodyAsStream();
out = new ByteArrayOutputStream(READ_BUFFER_SIZE);
while ((len = in.read(buff)) != -1 && byteCount <= RESPONSE_SIZE_LIMIT) {
byteCount += len;
out.write(buff, 0, len);
}
if (byteCount >= RESPONSE_SIZE_LIMIT) {
throw new IOException(
"Size limited exceeded reading from HTTP input stream");
}
return (out);
}