出現異常的代碼塊如下:
CloseableHttpClient httpClient = getHttpClient();
// 調用HttpClient發送Http請求,並對響應進行處理,轉換成字節數組
HttpResponse response;
response = httpClient.execute(method);
byte[] bytes = EntityUtils.toByteArray(response.getEntity());----出現異常的行。
異常翻譯:Premature end of chunk coded message body: closing chunk expected
翻譯如下:過早的關閉通過塊編碼的消息體:關閉塊異常。
關鍵點在於http傳輸協議1.0與1.1的區別,1.1協議的內容是分塊傳輸,response獲得實體事懶加載,一塊一塊的獲取,但是這個EntityUtils工具類的.toByteArray方法實現如下:
public static byte[] toByteArray(final HttpEntity entity) throws IOException {
Args.notNull(entity, "Entity");
final InputStream instream = entity.getContent();
if (instream == null) {
return null;
}
try {
Args.check(entity.getContentLength() <= Integer.MAX_VALUE,
"HTTP entity too large to be buffered in memory");
int capacity = (int)entity.getContentLength();
if (capacity < 0) {
capacity = DEFAULT_BUFFER_SIZE;
}
final ByteArrayBuffer buffer = new ByteArrayBuffer(capacity);
final byte[] tmp = new byte[DEFAULT_BUFFER_SIZE];
int l;
while((l = instream.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
return buffer.toByteArray();
} finally {
instream.close();
}
}
獲取結束立馬將流關閉了,但是傳輸還沒有結束了呢,所以就出現了上面的異常信息。
解決方案,設置http傳輸協議版本,改爲1.0,這樣消息體就會一次性全部傳過來;
HttpPost post = new HttpPost(builderUrl(url, requestParams));
post.setProtocolVersion(HttpVersion.HTTP_1_0);
其他參考鏈接:
https://www.cnblogs.com/zengweiming/p/9364372.html
https://blog.csdn.net/c364902709/article/details/80828376
https://blog.csdn.net/u012175637/article/details/82467130