使用HttpURLConnection(实现单线程多线程下载)

HttpURLConnection继承URLConnection因此也可向指定网站发送POST,GET请求

单线程下载 AsyncTask<String, Integer, String> {@Overrideprotected void onProgressUpdate(Integer… values) {super.onProgressUpdate(values);// int count= Integer.parseInt(values[1]*100.0/values[0]);mProgressBar.setProgress((int) (values[0] * 100.0 / values[1]));}@Overrideprotected String doInBackground(String… params) {try {URL url = new URL(“http://192.168.0.30:8080/MyWebTest/music/aa.mp3”);URLConnection connection = url.openConnection();int length = connection.getContentLength();//publishProgress(length);InputStream is = connection.getInputStream();File file = new File(Environment.getExternalStorageDirectory(), “aa.mp3”);if (!file.exists()) {file.createNewFile();}FileOutputStream os = new FileOutputStream(file);byte[] array = new byte[1024];int sum = 0;int index = is.read(array);while (index != -1) {os.write(array, 0, index);sum += index;publishProgress(sum, length);index = is.read(array);}os.flush();os.close();is.close();} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}@Overrideprotected void onPostExecute(String s) {super.onPostExecute(s);}}多线程下载步骤

【1】创建URL对象 【2】获取指定URL对象指向的资源的大小,getContentLength()方法实现; 【3】在本地磁盘创建与资源大小相当的文件 【4】计算每个线程应该下载资源的分配(从那个字节开始,到哪个字节结束) 【5】依次创建启动多个线程下载

() {new Thread() {() {String urlPath = “http://192.168.0.30:8080/MyWebTest/music/aa.mp3”;try {URL url = new URL(urlPath);URLConnection connection = url.openConnection();length = connection.getContentLength();File file = new File(Environment.getExternalStorageDirectory(), “cc.mp3”);if (!file.exists()) {file.createNewFile();}MultiThread[] threads = new MultiThread[5];for (int i = 0; i < 5; i++) {MultiThread thread = null;if (i == 4) {thread = new MultiThread(length / 5 * 4, length, urlPath, file.getAbsolutePath());} else {thread = new MultiThread(length / 5 * i, length / 5 * (i + 1)-1, urlPath, file.getAbsolutePath());}thread.start();threads[i] = thread;}boolean isFinish = true;while (isFinish) {int sum = 0;for (MultiThread thread : threads) {sum += thread.getSum();}Message msg = handler.obtainMessage();msg.what = 0x23;msg.arg1 = sum;handler.sendMessage(msg);if (sum + 10 >= length) {isFinish = false;}Thread.sleep(1000);}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}}}.start();}{public MultiThread(long start, long end, String url, String filePath) {this.start = start;this.end = end;this.urlPath = url;this.filePath = filePath;}private int sum=0;private long start;private long end;private String urlPath;private String filePath;() {return sum;}() {try {URL url = new URL(urlPath);URLConnection connection=url.openConnection();connection.setAllowUserInteraction(true);connection.setRequestProperty(“Range”,”byte=”+start+”-“+end);InputStream is=connection.getInputStream();byte[] array=new byte[1024];is.read(array);File file=new File(filePath);RandomAccessFile randomAccessFile=new RandomAccessFile(file,”rw”);randomAccessFile.seek(start);int index=is.read(array);while(index!=-1){randomAccessFile.write(array,0,index);sum+=index;index=is.read(array);}randomAccessFile.close();is.close();} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}.OnClickListener {private Button mButtonSingle;private Button mButtonMilti;private ProgressBar mProgressBar;private int length;private Handler handler = new Handler() {(Message msg) {switch (msg.what) {case 0x23:mProgressBar.setProgress(msg.arg1 * 100 / length);break;default:break;}}};(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_download);mButtonSingle = (Button) findViewById(R.id.button_download_single);mButtonMilti = (Button) findViewById(R.id.button_download_milti);mProgressBar = (ProgressBar) findViewById(R.id.progressbar);mButtonMilti.setOnClickListener(this);mButtonSingle.setOnClickListener(this);}(View v) {switch (v.getId()) {case R.id.button_download_single:SingleDownloadTask task = new SingleDownloadTask();task.execute();break;case R.id.button_download_milti:MultiThreadDownload();break;default:break;}}() {new Thread() {() {String urlPath = “http://192.168.0.30:8080/MyWebTest/music/aa.mp3”;try {URL url = new URL(urlPath);URLConnection connection = url.openConnection();length = connection.getContentLength();File file = new File(Environment.getExternalStorageDirectory(), “cc.mp3”);if (!file.exists()) {file.createNewFile();}MultiThread[] threads = new MultiThread[5];for (int i = 0; i < 5; i++) {MultiThread thread = null;if (i == 4) {thread = new MultiThread(length / 5 * 4, length, urlPath, file.getAbsolutePath());} else {thread = new MultiThread(length / 5 * i, length / 5 * (i + 1)-1, urlPath, file.getAbsolutePath());}thread.start();threads[i] = thread;}boolean isFinish = true;while (isFinish) {int sum = 0;for (MultiThread thread : threads) {sum += thread.getSum();}Message msg = handler.obtainMessage();msg.what = 0x23;msg.arg1 = sum;handler.sendMessage(msg);if (sum + 10 >= length) {isFinish = false;}Thread.sleep(1000);}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}}}.start();}class SingleDownloadTask extends AsyncTask<String, Integer, String> {(Integer… values) {super.onProgressUpdate(values);// int count= Integer.parseInt(values[1]*100.0/values[0]);mProgressBar.setProgress((int) (values[0] * 100.0 / values[1]));}@Overrideprotected String doInBackground(String… params) {try {URL url = new URL(“http://192.168.0.30:8080/MyWebTest/music/aa.mp3”);URLConnection connection = url.openConnection();int length = connection.getContentLength();//publishProgress(length);InputStream is = connection.getInputStream();File file = new File(Environment.getExternalStorageDirectory(), “aa.mp3”);if (!file.exists()) {file.createNewFile();}FileOutputStream os = new FileOutputStream(file);byte[] array = new byte[1024];int sum = 0;int index = is.read(array);while (index != -1) {os.write(array, 0, index);sum += index;publishProgress(sum, length);index = is.read(array);}os.flush();os.close();is.close();} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}(String s) {super.onPostExecute(s);}}}

,开始的时侯,我们就知道,总会有终结。

使用HttpURLConnection(实现单线程多线程下载)

相关文章:

你感兴趣的文章:

标签云: