您的位置:首页 > 理论基础 > 计算机网络

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

2015-09-12 08:57 483 查看
HttpURLConnection继承URLConnection因此也可向指定网站发送POST,GET请求

单线程下载

class SingleDownloadTask extends AsyncTask<String, Integer, String> {

        @Override
        protected 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]));
        }

        @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();
                //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;

        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

        }

    }


多线程下载步骤

【1】创建URL对象

【2】获取指定URL对象指向的资源的大小,getContentLength()方法实现;

【3】在本地磁盘创建与资源大小相当的文件

【4】计算每个线程应该下载资源的分配(从那个字节开始,到哪个字节结束)

【5】依次创建启动多个线程下载

private void MultiThreadDownload() {
        new Thread() {

            @Override
            public void run() {
                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 class MultiThread extends Thread{
    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;

    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","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();
        }

    }

}


public class DownloadActivity extends Activity implements View.OnClickListener {

private Button mButtonSingle;
private Button mButtonMilti;
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;
default:
break;
}
}
};

@Override
protected void onCreate(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);
}

@Override
public void onClick(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;

}

}

private void MultiThreadDownload() { new Thread() { @Override public void run() { 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> { @Override protected 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])); } @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(); //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; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); } }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: