文件上传下载原理

本文介绍了一种在Android应用中实现图片及文件下载的方法。通过使用Handler机制更新UI,实现从网络获取图片并显示,同时提供了多线程下载文件的示例代码。
图片下载
private EditText et_path;
private TextView tv_result;

//1、在主线程中创建handler的成员变量
private Handler handler = new Handler(){
// 3、主线程授权handler,hanlder修改UI界面
/**
* 接收并处理消息
* msg 在子线程传递过来的消息对象
*/
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//修改U界面
String result = (String) msg.obj;
tv_result.setText(result);
}
};


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

et_path = (EditText) findViewById(R.id.et_path);
tv_result = (TextView) findViewById(R.id.tv_result);
}


public void getHTML(View view){
final String path = et_path.getText().toString().trim();

if(TextUtils.isEmpty(path)){
Toast.makeText(this, "页面的路径不能为空", 0).show();
return;
}else{
//访问网络获取页面的数据
new Thread(){
public void run() {
// 访问网络,从网络上获取图片的数据,并且现在imageview
try {
// 1、创建URL对象,打开一个HTTP类型的连接:
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
// 2、设置请求方式GET、POST,连接的超时时间等请求参数:
conn.setRequestMethod("GET");// 默认是GET方式,要大写
conn.setReadTimeout(3000);
// conn.setRequestProperty("Accept-Language", "zh-CN");
// 3、得到服务器端返回的响应数据(以二进制流的形式返回响应数据),判断响应码是不是200请求成功、404找不到资源、503服务器端内部错误:
//判断响应码是不是200
int code = conn.getResponseCode();
if(200 == code){
InputStream is  = conn.getInputStream();
// 4、把二进制流的响应数据转换成需要的数据类型:
String  result = StreamTools.readStreamToStr(is);
//在imageview上显示一张图片
// iv.setImageBitmap(bm);

// 2、在子线程中得到handler的引用,调用handler的sendMessage,给主线程发送一个消息,我要修改UI界面了
//创建一个消息对象,消息盒子
Message msg = new Message();
msg.obj = result;

handler.sendMessage(msg);
}

} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}

}

//发  送用户名密码数据 ,获得成功或者失败

// 访问网络,从网络上获取图片的数据,并且现在imageview
try {
String path="http://192.168.1.254:8080/web/servlet/LoginServlet";
// 1、创建URL对象,打开一个HTTP类型的连接:
// String data = "username="+URLEncoder.encode(username,"UTF-8")+"&password="+URLEncoder.encode(pwd,"UTF-8");

// 1、创建一个浏览器:
HttpClient client = new DefaultHttpClient();

// 2、输入网址:
HttpPost httpPost = new HttpPost(path);
//封装需要提交的数据
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
BasicNameValuePair pair1 = new BasicNameValuePair("username", username);
BasicNameValuePair pair2 = new BasicNameValuePair("password", pwd);

list.add(pair1);
list.add(pair2);
//把需要提交的数据封装到form实体中
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
//把数据实体放到post对象
httpPost.setEntity(entity);
// 3、敲回车,发送请求:
HttpResponse response = client.execute(httpPost);

int code = response.getStatusLine().getStatusCode();
if(200 == code){
InputStream is  = response.getEntity().getContent();
// 4、把二进制流的响应数据转换成需要的数据类型:
String result = StreamTools.readStreamToStr(is);

Message msg = Message.obtain();
//定义一个消息码,用来区分消息从什么地方发送的
msg.what = SUCCESS;
msg.obj = result;
handler.sendMessage(msg);
}

} catch (Exception e) {
Message msg = Message.obtain();
//定义一个消息码,用来区分消息从什么地方发送的
msg.what = FAILED;
msg.obj = "网络异常,获取数据失败";
handler.sendMessage(msg);

e.printStackTrace();


多线程下载



//设置正在运行的线程的个数
private  int runningThreadCount;

public DownLoadChildThread(String path, int threadId, int startIndex,
int ednIndex,int runningThreadCount) {
this.path = path;
this.threadId = threadId;
this.startIndex = startIndex;
this.ednIndex = ednIndex;
this.runningThreadCount = runningThreadCount;
}

@Override
public void run() {
try {
//5、创建子线程,下载数据:
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("GET");
conn.setReadTimeout(3000);

//设置请求的数据范围
conn.setRequestProperty("Range", "bytes="+startIndex+"-"+ednIndex);
System.out.println("线程"+threadId+"下载的范围:"+startIndex+"-"+ednIndex);
//请求部分数据成功,响应码为206
int code = conn.getResponseCode();
if(code == 206){
InputStream is = conn.getInputStream();
RandomAccessFile raf = new RandomAccessFile(Environment.getExternalStorageDirectory()+"/temp.exe", "rw");
//从指定的位置开始写数据
raf.seek(startIndex);
byte[] buffer = new byte[1024];
int len = -1;
while((len = is.read(buffer)) != -1){
raf.write(buffer, 0, len);
}
is.close();
raf.close();
System.out.println("线程"+threadId+"下载完成........................");

//每个子线程下载完成时都去减1
synchronized (DownLoadChildThread.class) {
runningThreadCount--;
if(runningThreadCount == 0){
System.out.println("文件下载完成...........................");
}
}
}

} catch (Exception e) {
e.printStackTrace();
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值