public byte[] getResponseBody() throws IOException {
        if (this.responseBody == null) {
            InputStream instream = getResponseBodyAsStream();
            if (instream != null) {
                long contentLength = getResponseContentLength();为何要判断流数据包含字符数呢?字符数大于Integer.MAX_VALUE,为何就不能返回呢?求知道:)
                if (contentLength > Integer.MAX_VALUE) { //guard below cast from overflow
                    throw new IOException("Content too large to be buffered: "+ contentLength +" bytes");
                }
                int limit = getParams().getIntParameter(HttpMethodParams.BUFFER_WARN_TRIGGER_LIMIT, 1024*1024);
                if ((contentLength == -1) || (contentLength > 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 > 0 ? (int) contentLength : DEFAULT_INITIAL_BUFFER_SIZE);
                byte[] buffer = new byte[4096];
                int len;
                while ((len = instream.read(buffer)) > 0) {
                    outstream.write(buffer, 0, len);
                }
                outstream.close();
                setResponseStream(null);
                this.responseBody = outstream.toByteArray();
            }
        }
        return this.responseBody;
    }

解决方案 »

  1.   

    String的length要记住是int
    int 的最大值是Integer.MAX_VALUE。
      

  2.   

    应该是防止缓冲区的溢出攻击。下边有代码:
     ByteArrayOutputStream outstream = new ByteArrayOutputStream(
      contentLength > 0 ? (int) contentLength : DEFAULT_INITIAL_BUFFER_SIZE);ByteArrayOutputStream构造函数需要传递一个int型参数,这里将contentLength强转成int型,所以如果contentLength数值超过了int的最大值会变成负值,就会抛IllegalArgumentException,程序在方法的前面对一些有效性做检查而不是放在后面等出错,这属于"防御性编程",代码更健壮。
      

  3.   

    这个是一个警告:常用的HttpMethodBase.getResponseBodyAsString方法如果获取长响应,可能会出现字节丢失,建议使用HttpMethodBase.getResponseBodyAsStream方法,对流进行取值处理。