Response size limit when using Apache HttpComponents

只愿长相守 提交于 2020-01-05 07:35:09

问题


I am converting some code from the Http Client 3.x library over to the Http Components 4.x library. The old code contains a check to make sure that the response is not over a certain size. This is fairly easy to do in Http Client 3.x since you can get back a stream from the response using the getResponseBodyAsStream() method and determine when the size has been exceeded. I can't find a similar way in Http Components.

Here's the old code as an example of what I'm trying to do:

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);

}

回答1:


You can use HttpEntity.getContent() to get an InputStream to read from yourself.



来源:https://stackoverflow.com/questions/12482160/response-size-limit-when-using-apache-httpcomponents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!