1
我將一些代碼從Http Client 3.x庫轉換爲Http Components 4.x庫。舊代碼包含一個檢查以確保響應未超過特定大小。這在Http Client 3.x中很容易實現,因爲您可以使用getResponseBodyAsStream()方法從響應中獲取流並確定何時超出大小。我無法在Http組件中找到類似的方法。使用Apache HttpComponents時的響應大小限制
這裏的舊代碼的什麼,我試圖做一個例子:
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);
}
你看過HttpEntity.getContent()嗎? –
工作,謝謝! – acvcu
我會將它添加爲答案,然後讓其他人更容易找到答案。 –