Java-httpClient警告: Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.


使用HttpClient,總是報出“Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.”的WARN日志,定位到HttpClient的源碼如下:

public abstract class HttpMethodBase
    implements HttpMethod
{
...
    public byte[] getResponseBody() throws IOException {
        if (responseBody == null) {
            InputStream instream = getResponseBodyAsStream();
            if (instream != null) {
                long contentLength = getResponseContentLength();
                if (contentLength > 2147483647L){
                    throw new IOException("Content too large to be buffered: " + contentLength + " bytes");
          }
int limit = getParams().getIntParameter("http.method.response.buffer.warnlimit", 1048576); if (contentLength == -1L || contentLength > (long) limit){ LOG.warn("Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.");
          } LOG.debug(
"Buffering response body"); ByteArrayOutputStream outstream = new ByteArrayOutputStream(contentLength <= 0L ? 4096: (int) contentLength); byte buffer[] = new byte[4096]; int len; while ((len = instream.read(buffer)) > 0){
            outstream.write(buffer,
0, len);
          } outstream.close(); setResponseStream(
null); responseBody = outstream.toByteArray(); } } return responseBody; } ... }

WARN的條件是((contentLength == -1) || (contentLength > limit)),也就是說,或者是返回的HTTP頭沒有指定contentLength,或者是contentLength大於上限(默認是1M)。如果能確定返回結果的大小對程序沒有顯著影響,這個WARN就可以忽略,可以在日志的配置中把HttpClient的日志級別調到ERROR,不讓它報出來。

 

 當然,這個警告也是有意義的,HttpClient建議使用InputStream getResponseBodyAsStream()代替byte[] getResponseBody()。對於返回結果很大或無法預知的情況,就需要使用InputStreamgetResponseBodyAsStream(),避免byte[] getResponseBody()可能帶來的內存的耗盡問題。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM