Android网络连接----使用URLConnection实现从服务器上下载
2015-09-14 21:33
603 查看
单线程下载
package com.test.shiweiwe.networkapp; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import com.test.shiweiwe.networkapp.mutildownloadthread.MultiDownload; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; /** * Created by Administrator on 2015/9/11. */ public class DownLoadDemo extends Activity implements View.OnClickListener{ private Button mButtonSingle; private ProgressBar mProgressBar; private int length; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_download); mProgressBar= (ProgressBar) findViewById(R.id.progressbar); mButtonSingle= (Button) findViewById(R.id.single_download); mButtonSingle.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.single_download: myDownload down= new myDownload(); down.execute(); break; } } class myDownload extends AsyncTask<String,Integer,String>{ @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); mProgressBar.setProgress((int) (values[0]/values[1]*100.0)); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); } @Override protected 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(); InputStream inputStream = connection.getInputStream(); File file = new File(Environment.getExternalStorageDirectory(),"aa.mp3"); if(!file.exists()){ file.createNewFile(); } FileOutputStream outputStream = new FileOutputStream(file); byte[] bytes = new byte[1024]; int sum = 0; int index = inputStream.read(bytes); while(index!=-1){ outputStream.write(bytes,0,index); sum+=index; publishProgress(sum,length); index=inputStream.read(bytes); } outputStream.flush(); outputStream.close(); inputStream.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } } }
多线程下载
package com.test.shiweiwe.networkapp.mutildownloadthread; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; /** * Created by Administrator on 2015/9/13. */ public class MultiDownload extends Thread{ private int sum=0; private long start; private long end; private String urlPath; private String filePath; public MultiDownload(long start, long end, String url, String filePath) { this.start = start; this.end = end; this.urlPath = url; this.filePath = filePath; } public int getSum() { return sum; } @Override public void run() { try { URL url=new URL(urlPath); URLConnection connection=url.openConnection(); connection.setAllowUserInteraction(true);//允许用户交互 connection.setRequestProperty("Range", "bytes=" + start + "-" + end);// InputStream is= connection.getInputStream(); byte [] array=new byte[1024]; // is.read(array); File file=new File(filePath); RandomAccessFile randomAccessFileile=new RandomAccessFile(file,"rw");//允许随机读写 randomAccessFileile.seek(start);//找到文件的头 int index=is.read(array); while (index!=-1){ randomAccessFileile.write(array,0,index); sum+=index; index=is.read(array); } randomAccessFileile.close(); is.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
package com.test.shiweiwe.networkapp; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import com.test.shiweiwe.networkapp.mutildownloadthread.MultiDownload; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; /** * Created by Administrator on 2015/9/11. */ public class DownLoadDemo extends Activity implements View.OnClickListener { private Button mButtonSingle; private Button mButtonMul; private ProgressBar mProgressBar; private int length; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0x23: mProgressBar.setProgress(msg.arg1 * 100 / length); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_download); mProgressBar = (ProgressBar) findViewById(R.id.progressbar); mButtonMul = (Button) findViewById(R.id.mul_download); mButtonMul.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.mul_download: new Thread(new Runnable() { @Override public void run() { try { // String urlPath="http://192.168.0.30:8080/MyWebTest/music/aa.mp3"; String urlPath = "http://192.168.0.55:8088/WebTest/hello.jpg"; URL url = new URL(urlPath); URLConnection connection = url.openConnection(); length = connection.getContentLength(); File file = new File(Environment.getExternalStorageDirectory(), "dd.jpg"); if (!file.exists()) { file.createNewFile(); } MultiDownload[] threads = new MultiDownload[5]; for (int i = 0; i < 5; i++) {//包前包后 MultiDownload thread = null; if (i == 4) { thread = new MultiDownload(length / 5 * 4, length, urlPath, file.getAbsolutePath()); } else { thread = new MultiDownload(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 (MultiDownload 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(); break; } } }
相关文章推荐
- Android第九讲——网络(一)
- (4.4.12)Android开发:如何实现TCP和UDP传输
- URLConnection/Android Stutio中HttpClient的添加jar包方法和DoGet、DoPost的用法
- Android网络连接----使用URLConnection连接网络简单例子
- (5.2.3) 写给那些让我糊里糊涂的HTTP、TCP、UDP、Socket
- Httpclient
- n-1位数(http://acm.nyist.net/JudgeOnline/problem.php?pid=96)
- 网络连接之——xUtils 介绍(三)
- Android0912<十七>(Android 网络URLConnection)(ing多线程下载)
- Android网络连接---xUtils(HttpUtils)
- Android网络技术
- hdu 5438 Ponds(长春网络赛 拓扑+bfs)
- 第三十八天 网络连接:Volley、xUtils
- Java网络编程之Socket的使用
- HDU 5442 Favorite Donut (2015年长春赛区网络赛F题)
- Android网络连接---Google网络库Volley
- 超文本传输协议,http请求过程
- android HttpClient的使用
- HDU 5438 Ponds(2015ACM长春网络赛+枚举删点+DFS求联通块)
- Machine Learning 网络资源