Android网络连接----使用URLConnection实现从服务器上下载

单线程下载

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;
        }

    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值