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

Android_HttpURLConnection下载文件

2014-07-26 19:53 393 查看
1.读取txt.. 等文件

util类。

package com.raise.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpDownloader {
private URL url = null;

/**
* 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文件当中的内容
* 1.创建一个URL对象
* 2.通过URL对象,创建一个HttpURLConnection对象
* 3.得到InputStram
* 4.从InputStream当中读取数据
* @param urlStr
* @return
*/
public String download(String urlStr) {
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader buffer = null;
try {
// 创建一个URL对象
url = new URL(urlStr);
// 创建一个Http连接
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
// 使用IO流读取数据
buffer = new BufferedReader(new InputStreamReader(urlConn
.getInputStream()));
while ((line = buffer.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
buffer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return sb.toString();
}

}


Activity类

TextView testView;
String result;
HttpDownloader httpDownloader = new HttpDownloader();
@SuppressLint("HandlerLeak")
Handler handler = new Handler(){

public void handleMessage(android.os.Message msg) {
if (msg.what == 0x123) {
testView.setText(result+"---->");
}

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

testView = (TextView) findViewById(R.id.testText);
new Thread(){
public void run() {
try {
String urlStr = "http://10.18.33.25/mp3/nrnr.lrc";
result = httpDownloader.download(urlStr);
Log.i("---->",result+"----");
handler.sendEmptyMessage(0x123);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
};
}.start();
}


注意,下载文件不能再mian线程中进行。

asyncTask下载文件

// 异步任务来下载音乐文件
class DownTask extends AsyncTask<Mp3Info, Integer, String> {

// 进度条
ProgressDialog progressDialog;
// 读取字节数
int hasRead = 0;
Context mContext;

public DownTask(Context mContext) {
super();
this.mContext = mContext;
}

@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(mContext);
// 设置标题
progressDialog.setTitle("任务正在异步下载");
// 设置不能被取消按钮关闭
// progressDialog.setCancelable(false);
// 进度条的风格
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// 是否显示进度条的进度
progressDialog.setIndeterminate(false);

}

@Override
protected String doInBackground(Mp3Info... params) {
Mp3Info mp3Info = params[0];
String urlStr = LOCALHOST + "mp3/" + mp3Info.getMp3name();

InputStream is = null;
OutputStream os = null;
try {
// 下载文件,显示进度条
// 设置内容
progressDialog.setMessage("正在下载:"+mp3Info.getMp3name());
// 设置进度条最大进度值
progressDialog.setMax(Integer.parseInt(mp3Info.getMp3size()));
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
is = conn.getInputStream();
// 创建文件夹和文件
fileUtils.creatSDDir("mp3");
File file = fileUtils
.creatSDFile("mp3/" + mp3Info.getMp3name());
// 写入文件
os = new FileOutputStream(file);
byte buffer[] = new byte[4*1024];
int len=-1;
while ((len = is.read(buffer)) != -1) {
os.write(buffer,0,len);
hasRead += 1024;
publishProgress(hasRead);
}
os.flush();
return "下载成功";
} catch (Exception e) {
e.printStackTrace();
return "下载文件出错";
} finally {
try {
if (is!=null) {
is.close();
}
if (os!=null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT)
.show();
}

@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressDialog.show();
progressDialog.setProgress(values[0]);
}

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