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

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

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: