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

HttpURLConnection 下载

2015-07-25 13:28 369 查看
1.

package com.example.xxxxxx;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

import java.util.LinkedHashMap;

import java.util.Map;

import android.util.Log;

public class T extends Thread {

private String downUrl;

private int fileSize;

private HttpURLConnection http;

private boolean isCancel;

private InputStream is;

private FileOutputStream os;

public boolean isCancel() {

return isCancel;

}

public void setCancel(boolean isCancel) {

this.isCancel = isCancel;

}

public T(String downUrl) {

this.downUrl = downUrl;

}

public void setCancel() {

this.isCancel = true;

if (http != null) {

try {

if (is != null) {

is.close();

}

} catch (Exception e) {

// TODO Auto-generated catch block

// e.printStackTrace();

}

http.disconnect();

http = null;

}

Log.i("zdy", "isCancel");

}

public void run() {

try {

URL imageUrl = new URL(downUrl);

http = (HttpURLConnection) imageUrl.openConnection();

http.setConnectTimeout(5 * 1000);

http.setRequestMethod("GET");

http.setRequestProperty(

"Accept",

"image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint,
application/msword, */*");

http.setRequestProperty("Accept-Language", "zh-CN");

http.setRequestProperty("Charset", "UTF-8");

http.setRequestProperty(

"User-Agent",

"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");

http.setRequestProperty("Connection", "Keep-Alive");

http.connect();

Log.i("zdy", "---" + System.currentTimeMillis());

if (http.getResponseCode() == 200) {

this.fileSize = http.getContentLength();// 根据响应获取文件大小

Log.i("zdy", "---" + System.currentTimeMillis());

if (fileSize <= 0) {

Log.i("zdy", "--->" + "文件大小错误");

} else {

is = http.getInputStream();

os = new FileOutputStream(new File(

MainActivity.LOCAL_APK_PATH, "zdy.jpg"));

// Utils.CopyStream(is, os);

final int buffer_size = 1024;

byte[] bytes = new byte[buffer_size];

int offset = 0;

int count = 0;

while (!isCancel

&& (offset = is.read(bytes, 0, buffer_size)) != -1) {

os.write(bytes, 0, offset);

Log.i("zdy", "--->" + "下载中。。。。");

count += offset;

}

if (count == fileSize) {

Log.i("zdy", "完成");

}

Log.i("zdy", "线程结束");

}

} else {

}

} catch (MalformedURLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

Log.i("zdy", "url 格式错误");

} catch (Exception e) {

Log.i("zdy", "网络连接失败");

if (isCancel == true) {

Log.i("zdy", "无网络连接+手动取消");

}

e.printStackTrace();

} finally {

if (is != null) {

try {

is.close();

is = null;

} catch (IOException e) {

// TODO Auto-generated catch block

// e.printStackTrace();

}

}

if (os != null) {

try {

os.close();

os = null;

} catch (IOException e) {

// TODO Auto-generated catch block

// e.printStackTrace();

}

}

if (http != null) {

http.disconnect();

}

if (isCancel == true) {

Log.i("zdy", "下载取消");

}

}

}

/**

* 打印Http头字段

*

* @param http

*/

public void printResponseHeader(HttpURLConnection http) {

Map<String, String> header = getHttpResponseHeader(http);

for (Map.Entry<String, String> entry : header.entrySet()) {

String key = entry.getKey() != null ? entry.getKey() + ":" : "";

print(key + entry.getValue());

}

}

private void print(String msg) {

Log.i("zdy", "msg-》" + msg);

}

/**

* 获取Http响应头字段

*

* @param http

* @return

*/

public Map<String, String> getHttpResponseHeader(HttpURLConnection http) {

Map<String, String> header = new LinkedHashMap<String, String>();

for (int i = 0;; i++) {

String mine = http.getHeaderField(i);

if (mine == null)

break;

header.put(http.getHeaderFieldKey(i), mine);

}

return header;

}

}

// }

package com.example.xxxxxx;

import java.io.File;

import android.app.Activity;

import android.os.Bundle;

import android.os.Environment;

import android.view.Menu;

import android.view.View;

public class MainActivity extends Activity {

public static final String LOCAL_APK_PATH = Environment

.getExternalStorageDirectory() + "/zdy";

private String url = "http://www.ubtrobot.com/tools/alpha1robot/android/Alpha1Blooth(1.2.0.3).zip";

private T t;

private int index;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

File saveDir = new File(LOCAL_APK_PATH);// Environment.getExternalStorageDirectory();

if (!saveDir.exists()) {

saveDir.mkdirs();

}

t = new T(url);

}

public void onTest(View view) {

if (index == 0) {

if (t == null) {

t = new T(url);

}

t.start();

index++;

} else {

t.setCancel();

t = null;

index = 0;

}

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.main, menu);

return true;

}

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