apache.http.MalformedChunkCodingException: Chunked stream ended unexpectedly

产生的原因,应该是服务器返回的数据不是规范的格式 。
我使用的xutils的httpUtils来实现网络通信的,关于读取数据是在

StringDownloadHandler类中源代码

 inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charset));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line).append(' ');
current += OtherUtils.sizeOfString(line, charset);
if (callBackHandler != null) {
if (!callBackHandler.updateProgress(total, current, false)) {
break;
}
}
}
这样的实现,并不够健壮。

使用二进制的读取更加稳健

inputStream = entity.getContent();
byte data[] = new byte[40000];
long totalContactsCount = -1;
int readContactsCount = 0;
int currentByteReadCount = 0;
while ((currentByteReadCount = inputStream.read(data)) != -1) {
String readData = new String(data, 0, currentByteReadCount);
sb.append(readData);
// then +1 progress on every ...},{... (JSON object separator)
if (readData.indexOf("}~{") >= 0) {
readContactsCount++;
}

/* // publishing the progress....
if (totalContactsCount > 0) {
publishProgress((int)(readContactsCount * 100 / totalContactsCount));

}*/

}

参考

http://stackoverflow.com/questions/19486656/getting-malformedchunkcodingexception-while-reading-json-data

原文地址:https://www.cnblogs.com/naiking/p/5473244.html