开发者社区 问答 正文

Http stream read 读取字节问题

大家好,请教个问题:
使用HttpURLConnection从字节流中读取服务器过来的内容,发现在Android5.1.1的设备上,最多只能读取到8192字节。
同样的APP,放到Android4.4.4的另一个设备上,同样情况下则可以读取超过8192多得多的数据。
不知道是不是由于两个android版本不同,使用的Http lib不一样导致buffer size设置不一样。但是又找不到修改buffer size的地方。
代码如下:

 InputStream inStream = http.getInputStream();
 byte[] buffer = new byte[1024*64];
 int readBytes = 0;

try{
 while((readBytes = inStream.read(buffer, 0, buffer.length)) != -1 && !cancelled){
 Log.debug(this, "writeToFileMapping readBytes = " + readBytes);
 threadfile.write(buffer, 0, readBytes);
 downLength += readBytes;
 resetRetryTimes = true;
 }
 }finally{
 close(threadfile);
 close(inStream);
 }
 }

展开
收起
爵霸 2016-05-27 08:26:46 2305 分享 版权
1 条回答
写回答
取消 提交回答
  • http头部有一个ua字段标识客户端(服务器根据这个判断是Android/iPhone/电脑),有可能是这个造成的,对Android 5/4,服务器可能为设备特别定制一些东西 以确保网页以最佳模式显示。可以自己设置这个字段试试:

     connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Linux) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.122 Safari/534.30");

    这行代码将ua标识设置为Linux桌面,chrome浏览器

    2019-07-17 19:16:53
    赞同 展开评论
问答分类:
问答标签:
问答地址: