当前位置: 移动技术网 > IT编程>开发语言>Java > 基于java下载中getContentLength()一直为-1的一些思路

基于java下载中getContentLength()一直为-1的一些思路

2019年07月22日  | 移动技术网IT编程  | 我要评论

如果content length 在头文件中没有描述

暂时还没有解决方案

如果content long在头文件中有描述

方案一:

伪装成浏览器

conn.setrequestproperty("user-agent", " mozilla/5.0 (macintosh; intel mac os x 10_12_5) applewebkit/537.36 (khtml, like gecko) chrome/58.0.3029.110 safari/537.36"); 

代码中加入代理

string host = "127.0.0.1";  
   string port = "8888";  
   setproxy(host, port); 
   public static void setproxy(string host, string port) {  
  system.setproperty("proxyset", "true");  
  system.setproperty("proxyhost", host);  
  system.setproperty("proxyport", port);  
} 

方案二:

加入以下属性,让服务器不要gzip方式压缩:

java doc 有对此的描述:

by default, this implementation of httpurlconnection requests that servers use gzip compression. since getcontentlength() returns the number of bytes transmitted, you cannot use that method to predict how many bytes can be read from getinputstream(). instead, read that stream until it is exhausted: whenread() returns -1. 

conn.setrequestproperty("accept-encoding", "identity");

以上这篇基于java下载中getcontentlength()一直为-1的一些思路就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网