HttpURLConnection繼承了URLConnection,因此也可用於向指定網站發送GET請求、POST請求,而且它在URLConnection基礎上提供了如下便捷方法:
實現多線程下載的步驟:
下面用一個樣本來示範使用HttpURLConnection實現多線程下載。此代碼來源瘋狂講義一書,該代碼主要思路:在Activity中點擊按鈕,調用DownUtil的download()方法,在download()中啟動四個線程去下載資源,每個線程負責下載自己的那部分資源,代碼如下:
Activity:
package com.home.activity;import java.util.Timer;import java.util.TimerTask;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.ProgressBar;import com.home.multithreaddown.R;import com.home.util.DownUtil;public class MultiThreadDownActivity extends Activity {private EditText urlText;private EditText targetText;private Button downBtn;private ProgressBar bar;private DownUtil downUtil;private int mDownStatus;private Handler handler;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);// 擷取介面中控制項targetText = (EditText) findViewById(R.id.main_et_name);urlText = (EditText) findViewById(R.id.main_et_url);downBtn = (Button) findViewById(R.id.main_btn_download);bar = (ProgressBar) findViewById(R.id.main_progressBar);// 建立一個Handler對象handler = new Handler() {public void handleMessage(Message msg) {if (msg.what == 0x123) {bar.setProgress(mDownStatus);}}};downBtn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// 初始化DownUtil對象downUtil = new DownUtil(urlText.getText().toString(),targetText.getText().toString(), 4);try {// 開始下載downUtil.download();} catch (Exception e) {e.printStackTrace();}// 定義每秒調度擷取一次系統的完成進度final Timer timer = new Timer();timer.schedule(new TimerTask() {public void run() {// 擷取下載任務的完成比率double completeRate = downUtil.getCompleteRate();mDownStatus = (int) (completeRate * 100);// 發送訊息通知介面更新進度條handler.sendEmptyMessage(0x123);// 下載完成後取消任務調度if (mDownStatus >= 100) {timer.cancel();}}}, 0, 100);}});}}
下載的工具類(DownUtil):
package com.home.util;import java.io.InputStream;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.URL;public class DownUtil {// 定義下載資源的路徑private String path;// 指定所下載的檔案的儲存位置private String targetFile;// 定義需要使用多少線程下載資源private int threadNum;// 定義下載的檔案的總大小private int fileSize;// 定義下載的線程對象private DownloadThread[] threads;public DownUtil(String path, String targetFile, int threadNum) {this.path = path;this.threadNum = threadNum;// 初始化threads數組threads = new DownloadThread[threadNum];this.targetFile = targetFile;}public void download() throws Exception {URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout(5 * 1000);conn.setRequestMethod("GET");conn.setRequestProperty("Accept","image/gif,image/jpeg,image/pjpeg,application/x-shockwaveflash,application/x-ms-xbap,application/xaml+xml,application/vnd.ms-xpsdocument,application/x-ms-application,application/vnd.ms-excel,application/vnd.ms-powerpoint,application/msword,*/*");conn.setRequestProperty("Accept-Language", "zh-CN");conn.setRequestProperty("Charset", "UTF-8");conn.setRequestProperty("User-Agent","Mozilla/4.0(compatible;MSIE7.0;Windows NT 5.2;Trident/4.0;.NET CLR 1.1.4322;.NET CLR 2.0.50727;.NET CLR 3.0.04506.30;.NET CLR 3.0.4506.2152;.NET CLR 3.5.30729)");conn.setRequestProperty("Connection", "Keep-Alive");// 得到檔案大小fileSize = conn.getContentLength();conn.disconnect();int currentPartSize = fileSize / threadNum + 1;RandomAccessFile file = new RandomAccessFile(targetFile, "rw");// 設定本地檔案的大小file.setLength(fileSize);file.close();for (int i = 0; i < threadNum; i++) {// 計算每條線程的下載的開始位置int startPos = i * currentPartSize;// 每個線程使用一個RandomAccessFile進行下載RandomAccessFile currentPart = new RandomAccessFile(targetFile,"rw");// 定位該線程的下載位置currentPart.seek(startPos);// 建立下載線程threads[i] = new DownloadThread(startPos, currentPartSize,currentPart);// 啟動下載線程threads[i].start();}}/** * 擷取下載完成的百分比 * * @return */public double getCompleteRate() {// 統計多條線程已經下載的總大小int sumSize = 0;for (int i = 0; i < threadNum; i++) {sumSize += threads[i].length;}// 返回已經完成的百分比return sumSize * 1.0 / fileSize;}private class DownloadThread extends Thread {// 當前線程的下載位置private int startPos;// 定義當前線程負責下載的檔案大小private int currentPartSize;// 當前線程需要下載的檔案塊private RandomAccessFile currentPart;// 定義該線程已下載的位元組數private int length = 0;public DownloadThread(int startPos, int currentPartSize,RandomAccessFile currentPart) {this.startPos = startPos;this.currentPartSize = currentPartSize;this.currentPart = currentPart;}public void run() {try {URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout(5 * 1000);conn.setRequestMethod("GET");conn.setRequestProperty("Accept","image/gif,image/jpeg,image/pjpeg,application/x-shockwaveflash,application/x-ms-xbap,application/xaml+xml,application/vnd.ms-xpsdocument,application/x-ms-application,application/vnd.ms-excel,application/vnd.ms-powerpoint,application/msword,*/*");conn.setRequestProperty("Accept-Language", "zh-CN");conn.setRequestProperty("Charset", "UTF-8");InputStream is = conn.getInputStream();// 跳過startPos個字元,表明該線程只下載自己負責那部分檔案is.skip(startPos);byte[] by = new byte[1024];int hasRead = 0;// 讀取網路資料,並寫入本地檔案while (length < currentPartSize&& (hasRead = is.read(by)) != -1) {currentPart.write(by, 0, hasRead);// 累計該線程下載的總大小length += hasRead;}currentPart.close();is.close();} catch (Exception e) {e.printStackTrace();}}}}
Activity布局XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="輸入url:" /> <EditText android:id="@+id/main_et_url" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="輸入儲存的檔案名稱:" /> <EditText android:id="@+id/main_et_name" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> <Button android:id="@+id/main_btn_download" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="下載" /> <ProgressBar android:id="@+id/main_progressBar" style="@android:style/Widget.ProgressBar.Horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" /></LinearLayout>
許可權:
<!-- 在SD卡中建立與刪除檔案許可權 --><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/><!-- 向SD卡寫入資料許可權 --><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><!-- 授權訪問網路 --><uses-permission android:name="android.permission.INTERNET"/>