我最近在SO上问了这个问题:Grabbing JSON works from one link, not from another
我得到的答案基本上说服务器getContentLength
是可选的,所以我必须自己手动计算长度。嗯,我花了一些时间,但我想出了一些似乎得到正确数量的代码,但我不确定这是否是“正确”的方式。主要是因为我的while(0==0)
声明。
我得到的确切答案是:
content-length是响应服务器设置的标头。它是 可选,谷歌选择不发送它动态生成 内容(大多数服务器没有)。所以你必须阅读流,直到 你没有字节,而不是一次性完成。
所以这是我提出的代码:
Reader reader = new InputStreamReader(inputStream);
int contentLength=0;
int cur;
while (0==0){
cur = reader.read();
if (cur == -1) {
break;
} else {
contentLength++;
}
}
当服务器没有为您提供内容长度时,这似乎是一个可行的解决方案吗?
答案 0 :(得分:0)
您可以轻松计算服务器发送的InputStream
内容的字节长度,分为两行:
ByteArrayInputStream bais = new ByteArrayInputStream(inputStream);
int length = bias.toByteArray().length;
与您的方法相关:
int contentLength=0;
while (reader.read()>0){
contentLength++;
}
但是问题中提出的答案会发生什么:
int contentLength = connection.getContentLength();
那个是完全合理和可行的。