欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-09-15 10:44:34|栏目:JAVA代码|点击:

如果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利用自定义注解、反射实现简单BaseDao实例

栏    目:JAVA代码

下一篇:MyBatis框架中mybatis配置文件详细介绍

本文标题:基于java下载中getContentLength()一直为-1的一些思路

本文地址:http://www.codeinn.net/misctech/175228.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有