Android基於HttpUrlConnection類的檔案下載,
1 /** 2 * get方法的檔案下載 3 * <p> 4 * 特別說明 android中的progressBar是google唯一的做了處理的可以在子線程中更新UI的控制項 5 * 6 * @param path 7 */ 8 private void httpDown(final String path) { 9 new Thread() {10 @Override11 public void run() {12 URL url;13 HttpURLConnection connection;14 try {15 //統一資源16 url = new URL(path);17 //開啟連結18 connection = (HttpURLConnection) url.openConnection();19 //設定連結逾時20 connection.setConnectTimeout(4000);21 //設定允許得到伺服器的輸入資料流,預設為true可以不用設定22 connection.setDoInput(true);23 //設定允許向伺服器寫入資料,一般get方法不會設定,大多用在post方法,預設為false24 connection.setDoOutput(true);//此處只是為了方法說明25 //佈建要求方法26 connection.setRequestMethod("GET");27 //佈建要求的字元編碼28 connection.setRequestProperty("Charset", "utf-8");29 //設定connection開啟連結資源30 connection.connect();31 32 //得到連結地址中的file路徑33 String urlFilePath = connection.getURL().getFile();34 //得到url地址總檔案名稱 file的separatorChar參數表示檔案分離符35 String fileName = urlFilePath.substring(urlFilePath.lastIndexOf(File.separatorChar) + 1);36 //建立一個檔案對象用於儲存下載的檔案 此次的getFilesDir()方法只有在繼承至Context類的類中37 // 可以直接調用其他類中必須通過Context對象才能調用,得到的是內部儲存中此應用程式套件名下的檔案路徑38 //如果使用外部儲存的話需要添加檔案讀寫權限,5.0以上的系統需要動態擷取許可權 此處不在不做過多說明。39 File file = new File(getFilesDir(), fileName);40 //建立一個檔案輸出資料流41 FileOutputStream outputStream = new FileOutputStream(file);42 43 //得到連結的響應碼 200為成功44 int responseCode = connection.getResponseCode();45 if (responseCode == HttpURLConnection.HTTP_OK) {46 //得到伺服器響應的輸入資料流47 InputStream inputStream = connection.getInputStream();48 //擷取請求的內容總長度49 int contentLength = connection.getContentLength();50 51 //設定progressBar的Max52 mPb.setMax(contentLength);53 54 55 //建立緩衝輸入資料流對象,相對於inputStream效率要高一些56 BufferedInputStream bfi = new BufferedInputStream(inputStream);57 //此處的len表示每次迴圈讀取的內容長度58 int len;59 //已經讀取的總長度60 int totle = 0;61 //bytes是用於儲存每次讀取出來的內容62 byte[] bytes = new byte[1024];63 while ((len = bfi.read(bytes)) != -1) {64 //每次讀取完了都將len累加在totle裡65 totle += len;66 //每次讀取的都更新一次progressBar67 mPb.setProgress(totle);68 //通過檔案輸出資料流寫入從伺服器中讀取的資料69 outputStream.write(bytes, 0, len);70 }71 //關閉開啟的流對象72 outputStream.close();73 inputStream.close();74 bfi.close();75 76 runOnUiThread(new Runnable() {77 @Override78 public void run() {79 Toast.makeText(MainActivity.this, "下載完成!", Toast.LENGTH_SHORT).show();80 }81 });82 }83 84 } catch (Exception e) {85 e.printStackTrace();86 }87 }88 }.start();89 }
有不清楚的地方歡迎各位朋友們留言