从HTTPClient 3.1迁移到4.3.3,Method.getResponseBody(int)

时间:2015-03-31 15:24:50

标签: java apache-httpclient-4.x apache-commons-httpclient

我正在使用HTTPClient 3.1更新旧软件以使用HTTPClient 4.3.3。 我注意到在旧代码中有一个特定的要求:当获取远程页面/资源时,客户端能够验证维度,如果内容太大而无法下载完整资源,则会生成异常。 这是通过以下方式完成的:

int status = client.executeMethod(method);
...
byte[] responseBody= method.getResponseBody(maxAllowedSize+1);

注意maxAllowedSize之后的“+1”:要求提供原始页面/资源实际上太大的证据。 如果使用了最后一个字节,则抛出异常;否则页面已被处理。

我正在尝试在HTTPClient 4.3.3中实现相同的功能,但我找不到从服务器只下载一定数量字节的方法......这在我的应用程序中至关重要。 你能帮助我吗?提前谢谢。

旧的getResponseBody(int)方法的Javadoc:https://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/HttpMethodBase.html#getResponseBody(int)

1 个答案:

答案 0 :(得分:1)

通常应该直接从内容流中消费内容而不是在中间缓冲区中缓冲内容,但这与4.3 API大致相同:

CloseableHttpClient client = HttpClients.custom()
        .build();
try (CloseableHttpResponse response = client.execute(new HttpGet("/"))) {
    HttpEntity entity = response.getEntity();
    long expectedLen = entity.getContentLength();
    if (expectedLen != -1 && expectedLen > MAX_LIMIT) {
        throw new IOException("Size matters!!!!");
    }
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    InputStream inputStream = entity.getContent();
    byte[] tmp = new byte[1024];
    int chunk, total = 0;
    while ((chunk = inputStream.read(tmp)) != -1) {
        buffer.write(tmp, 0, chunk);
        total += chunk;
        if (total > MAX_LIMIT) {
            throw new IOException("Size matters!!!!");
        }
    }
    byte[] stuff = buffer.toByteArray();
}