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

来源:互联网 发布:python可以开发网站吗 编辑:程序博客网 时间:2024/06/05 02:26

下午写练习是发现 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;}


0 0
原创粉丝点击