getResponseBodyAsString()异常

本文介绍了一个常见问题:当HTTP响应体过大或未指定长度时,使用getResponseBodyAsString()方法会遇到警告。文章提供了代码示例说明如何通过getResponseBodyAsStream()方法解决此问题。
摘要由CSDN通过智能技术生成


在 使用 getResponseBodyAsString() 一直提示: Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is rec


<span style="font-size:18px;">public byte[] getResponseBody()
throws IOException
{
if (this.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 > 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 ? (int)contentLength : 4096);

byte[] buffer = new byte[4096];
int len;
while ((len = instream.read(buffer)) > 0)
{
int i;
outstream.write(buffer, 0, i);
}
outstream.close();
setResponseStream(null);
this.responseBody = outstream.toByteArray();
}
}
return this.responseBody;
}
//--------------------
public long getResponseContentLength()
{
Header[] headers = getResponseHeaderGroup().getHeaders("Content-Length");
if (headers.length == 0) {
return -1L;
}
if (headers.length > 1) {
LOG.warn("Multiple content-length headers detected");
}
for (int i = headers.length - 1; i >= 0; ) {
Header header = headers[i];
try {
return Long.parseLong(header.getValue());
} catch (NumberFormatException e) {
if (LOG.isWarnEnabled())
LOG.warn("Invalid content-length value: " + e.getMessage());
i--;
}

}

return -1L;
}</span>




如果返回的头信息没有指定长度或长度大于1M则抛出如上异常。
则需把 getResponseBodyAsString()换成 getResponseBodyAsStream()即可

<span style="font-size:18px;">InputStream inputStream = method.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer = new StringBuffer();
String str= "";
while((str = br.readLine()) != null){
stringBuffer .append(str );
}</span>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值