HttpURLConnection getContentLength值爲-1

HttpURLConnection getContentLength值爲-1

一個android項目有一個點擊更新可以下載更新apk,在更新時需要顯示一個進度,這裏用:

		URL url = new URL(downLoadPath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
       conn.setRequestMethod("GET");
       conn.setConnectTimeout(8 * 1000);
        conn.setReadTimeout(8 * 1000);
       conn.connect();
        long length = conn.getContentLength();

這樣取得文件的總長度,結果發現conn.getConentLength()取到的值 爲-1,查了一下有說設置 conn.setRequestProperty(“Accept-Encoding”, “identity”); 就可 了正常獲取長度了,添加後值還是-1。
於是把downLoadPath,下載地址放在瀏覽器上下載可以成功下展,看他NetWork:

在這裏插入圖片描述
這圖是我修改後的,修改前發現response裏並沒有content_lenght這個頭信息,所以獲取一直就是-1,然後去修改服務端,加上這個值:
resp.setHeader(“Content-Length”, String.valueOf(new FileInputStream(file).available()));
加上後便如上圖所示可以發現頭信息裏有了contentLength這個值,然後客戶端就可以成功獲取了,下面展示一下詳細代碼
服務端

private void fileLoad(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String param = req.getParameter("param") == null ? "" : req.getParameter("param");
		String callback = req.getParameter("callback") == null ? "" : req.getParameter("callback");
		String filename = req.getParameter("filename") == null ? "" : req.getParameter("filename");
		String tv = req.getParameter("tv") == null ? "" : req.getParameter("tv");

		JSONObject obj = new JSONObject();
		int recode = 0;
		String text = "";
		
		ServletOutputStream out = null;
		if (!filename.equals("")) {
			try {
				resp.setContentType("application/force-download");
				resp.setCharacterEncoding("utf-8");
				
				
				File file = null;
				if ("008".equals(tv)) {
					file = new File(MyIP.tv8_apk_download_url + filename);
				} else if ("009".equals(tv)) {
					file = new File(MyIP.tv9_apk_download_url + filename);
				}
				resp.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
				
				resp.setHeader("Content-Length", String.valueOf(new FileInputStream(file).available()));
				
				out = resp.getOutputStream();
				InputStream bis = null;
				BufferedOutputStream bos = null;
				try {
					bis = new FileInputStream(file);
					bos = new BufferedOutputStream(out);
					byte[] buff = new byte['?'];

					int bytesRead;
					int k = 0;
					while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
						k+=1;
						bos.write(buff, 0, bytesRead);
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (bis != null)
						bis.close();
					if (bos != null) {
						bos.close();
					}
				}
			} catch (NumberFormatException e) {
				recode = 1;
				text = "參數格式錯誤";
				e.printStackTrace();
			} catch (Exception e) {
				recode = 99;
				text = "系統異常";
				e.printStackTrace();

				OutputMethod.ExceptionControl(e, parameter);
			}
		} else {
			recode = 1;
			text = "缺少參數";
		}
		obj.put("recode", Integer.valueOf(recode));
		obj.put("text", text);
		System.out.println("####fileLoad:"+obj.toString());
		out.print(callback + "(" + obj.toString() + ")");
		out.close();
	}

客戶端

  private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    System.out.println("App的下載路徑爲:" + downLoadPath);

                    URL url = new URL(downLoadPath);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setRequestProperty("Accept-Encoding", "identity");
                    conn.setRequestProperty("User-Agent", " Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36");
                    conn.setConnectTimeout(8 * 1000);
                    conn.setReadTimeout(8 * 1000);
                    conn.connect();
                    long length = conn.getContentLength();

                    if(length < 0){
                        String values = conn.getHeaderField("Content-Length");
                        if (values != null && !values.isEmpty()) {
                            length = Long.parseLong(values);
                        }
                    }
                    InputStream is = conn.getInputStream();

                    System.out.println("#######conn.getContentLength:"+length);
                    //獲取App文件名
                    apkName = downLoadPath.substring(downLoadPath.lastIndexOf("=") + 1, downLoadPath.length());
                    System.out.println("####apkName:"+apkName);
                    //下載後保存的路徑
                    saveFileDir = Environment.getExternalStorageDirectory() + "/APP";
                    File apkFileDir = new File(saveFileDir);
                    if (!apkFileDir.exists()) {
                        //如果/App文件夾不存在就創建一個新的App子文件夾
                        apkFileDir.mkdir();
                    }
                    File apkFile = new File(apkFileDir, apkName);
                    FileOutputStream fos = new FileOutputStream(apkFile);

                    int count = 0;
                    byte buf[] = new byte[10 * 1024];
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        progress = (int) (((float) count / length) * 100);
                        //System.out.println("#####load progress:" + progress);
                        updateProgress.setProgress(progress);
                        if (numread <= 0) {

                            installAPk(apkFile);
                            break;
                        }
                        fos.write(buf, 0, numread);
                    } while (true);
                    fos.close();
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    ;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章