解决 HttpURLConnection类中getContentLength()方法返回-1问题


下午写练习是发现 conn.getContentLength()总是返回-1,经查阅很多资料才知道需要在conn.setRequestMethod("GET");后面增加一句
conn.setRequestProperty("Accept-Encoding", "identity"),才能获取到getContentLength()的值

URL url2 = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url2.openConnection();
conn.setConnectTimeout(5000);conn.setRequestMethod("GET");

conn.setRequestProperty("Accept-Encoding", "identity");

 if (conn.getResponseCode() == 200) { 
   maxLength = conn.getContentLength(); 
   mPbar.setMax(maxLength); 
   InputStream is = conn.getInputStream(); 
   String fileName = url.substring(url.lastIndexOf("/"));
   FileOutputStream os = new FileOutputStream(Constant.SD_CARD + "/" + fileName); 
   int len = 0;  
   byte[] buffer = new byte[1024];  
   while ((len = is.read(buffer)) != -1) {  
      this.publishProgress(len);
      os.write(buffer, 0, len);   
 }   
    os.close();   
    is.close();
    Bitmap  bitmap = BitmapFactory.decodeFile(Constant.SD_CARD + "/" + fileName); 
   return bitmap;
}



版权声明:本文为u011780218原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。