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;
}
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;
}
int 的最大值是Integer.MAX_VALUE。
ByteArrayOutputStream outstream = new ByteArrayOutputStream(
contentLength > 0 ? (int) contentLength : DEFAULT_INITIAL_BUFFER_SIZE);ByteArrayOutputStream构造函数需要传递一个int型参数,这里将contentLength强转成int型,所以如果contentLength数值超过了int的最大值会变成负值,就会抛IllegalArgumentException,程序在方法的前面对一些有效性做检查而不是放在后面等出错,这属于"防御性编程",代码更健壮。