HttpURLConnection getContentLength();返回时-1或者是0

出现问题:当getContentLength();返回时-1或者是0时候。

解决办法:需加上conn.setRequestProperty("Accept-Encoding", "identity");

解释:在默认情况下,HttpURLConnection 使用 gzip方式获取,文件 getContentLength()这个方法,每次read完成后可以获得,当前已经传送了多少数据,而不能用这个方法获取 需要传送多少字节的内容,当read() 返回 -1时,读取完成,由于这个压缩后的总长度我无法获取,那么进度条就没法计算值了。所以要取得长度则,要求http请求不要gzip压缩

附上一段代码:

 1                 // 临时文件检验, 是否续传文件
 2                 filePath = filePath + ".temp";
 3                 long haveDownLength = 0;
 4                 File tempFile = new File(filePath);
 5                 if (tempFile.exists())
 6                     haveDownLength = tempFile.length();
 7 
 8                 conn = (HttpURLConnection) new URL(urlString).openConnection();
 9                 if (haveDownLength > 0)
10                     conn.setRequestProperty("Connection", "Keep-Alive");
11                 conn.setReadTimeout(6000);
12                 conn.setConnectTimeout(3000);;
13                 conn.setRequestMethod("GET");
14                 conn.setRequestProperty("Accept-Encoding", "identity");
15                 conn.connect();
16 
17                 int fileSize = conn.getContentLength();
18                 long countRead = haveDownLength;
19                 if (conn.getResponseCode() == 200) {
20                     InputStream stream = conn.getInputStream();
21                     FileOutputStream fos = new FileOutputStream(filePath, haveDownLength > 0 ? true : false);
22                     int read = 0;
23 
24                     byte buffer[] = new byte[1024];
25                     while ((read = stream.read(buffer)) >= 0) {
26                         countRead += read;
27                         fos.write(buffer, 0, (int) read);
28                     }
29                     fos.flush();
30                     stream.close();
31                     fos.close();
32                 } else {
33                     fileSize = (int) haveDownLength;
34                 }
35                 conn.disconnect();
36 
37                 int index = filePath.indexOf(".temp");
38                 if (index >= 1) {
39                     String tempFilePath = filePath.substring(0, index);
40                     File renameFile = new File(filePath);
41                     File toFile = new File(tempFilePath);
42                     renameFile.renameTo(toFile);
43 
44                     String md5 = ControlDataSourceGlobalUtil.md5sum(tempFilePath);
45                     // MD5校验是否文件相同
46                     if (md5.compareToIgnoreCase(fileCrc32) != 0){
47                         File tempFilePathFile = new File(tempFilePath);
48                         tempFilePathFile.delete();
49                         return false;
50                     }
51                     return true;
52                 }
53             } catch (IOException e) {
54                 return false;
55             }

 

posted @ 2017-02-20 23:17  默默笙萧  阅读(9310)  评论(0编辑  收藏  举报