解决java网络下载获取不到文件长度

原文网址:http://blog.csdn.net/ashqal/article/details/7618330

原来网上代码一搜看到一段多点下载的代码,测试发现下载公司服务器上的文件的长度获取不到,源代码如下


[html] view plain copy
  1. HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();      
  2. //获得文件长度      
  3. long nEndPos =getFileSize(sURL);   

打印响应头后发现Transfer-Encoding: chunked


在HTTP1.1协议中,RFC 2616中14.41章节中定义的Transfer-Encoding: chunked的头信息,chunked编码定义在3.6.1中,所有HTTP1.1 应用都支持此使用trunked编码动态的提供body内容的长度的方式。


后来又搜罗了一把,最后发现HttpClient开源项目能解决,并且android集成了这包

[java] view plain copy
  1. HttpClient client = new DefaultHttpClient();  
  2. HttpGet httpGet = new HttpGet();  
  3. httpGet.setURI(new URI(urlStr));  
  4. HttpResponse response = client.execute(httpGet);  
  5. HttpEntity entity  = response.getEntity();  
  6. fileSize = entity.getContentLength();  
  7. client.getConnectionManager().shutdown();  
posted @ 2017-08-03 09:35  Philtell  阅读(516)  评论(0编辑  收藏  举报