需要的权限 访问互联网和读写SD卡
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
使用HttpURLConnection 其他函数方法访问网络步骤:
1. 得到URL 对象
2. 调用URL对象的openConnection方法, 并将返回值向下转型为HttpURLConnection 对象
URLConnection openConnection(Proxy proxy)
Returns a new connection to the resource referred to by this URL.
3. 调用HttpURLConnection对象的getInputStream()方法, 获取到字节流的网络数据
HttpURLConnection 其他常用函数
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(8000);
urlConnection.setReadTimeout(8000);
处理文本文件:
构建BufferedReader对象的好处是因为它有readLine()方法可以读取一行数据
inputStream 字节流 , inputStreamReader 把字节流转换成字符流,读出来的是一个个的字符, 处理起来还是很麻烦,
于是在字符流的基础上类似再套上一层管道BufferedReader,就可以一行一行的读取数据了
BufferedReader buffer = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()))
BufferedReader 按行读取返回的String对象,可以存储到StringBuffer中
String line = null;
StringBuffer sb = new StringBuffer();
while(line = buffer.readLine() != null ){
sb.append(line);
}
从输入流读取二进制文件后写入
OutputStream outputStream = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024 * 4] ;
int readLen ;
while( (readLen = input.read(buffer,0,buffer.length)) != -1 ) {
outputStream.write(buffer,0,readLen);
}
======================================================
访问SDCARD
判断是SD卡是否正常挂载
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
得到当前设备SD卡目录, Enviroment静态类的一个方法
Environment.getExternalStorageDirectory()
==================================================================
HttpDownloader 的部分代码, 下载文件
public class HttpDownloader {
// 开线程下载, 并保存到SD卡下指定的目录, 回调函数返回结果到主线程
public void downFile (final String urlStr, final String path,final String fileName, final HttpCallbackListener listener) {
// 如果没有SD卡的话 , 直接退出函数
if(! Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Log.d("SDCARD ERROR","无法访问SD卡");
return;
}
// 正常下载的话调用listener.onFinish("SUCCESS") 返回字符串SUCCESS,
// 文件存在则直接调用 onFinish("EXISTED")和onFinish("SUCCESS")返回EXISTED和SUCCESS,并不重新下载
// 异常和其他错误调用onError
new Thread(new Runnable(){
@Override
public void run() {
FileUtils fileUtil = new FileUtils();
//int result = -1;
if (fileUtil.isFileExist(path + fileName)){
if(listener != null) {
listener.onFinish("EXISTED");
}
}else {
InputStream input = null;
try {
input = getInputStreamFromUrl(urlStr);
//Log.d("SD 卡路径",fileUtil.getSDPATH());
File resultFile = fileUtil.write2SDFromInput(path, fileName, input);
//调用下载方法后, 一般如果出错的话异常会抛出的,如果返回的文件为null则下载失败,
if (resultFile == null) {
if(null != listener) {
listener.onError(new Exception("文件下载出错"));
}
}
} catch (Exception e) {
//创建URL对象异常, 下载异常, 对SD卡的IO异常 , 都可能在这里看LogCat调试
e.printStackTrace();
if(null != listener) {
listener.onError(e);
}
}finally {
try {
if (null != input ) input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//result = 0;
if(listener != null) {
listener.onFinish("SUCCESS");
}
}}).start();
}
public InputStream getInputStreamFromUrl(String urlStr) throws MalformedURLException, IOException {
URL url = new URL (urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
return connection.getInputStream();
}
}
=============================================================================================
回调接口类
public interface HttpCallbackListener {
void onFinish(String response);
void onError(Exception e);
}
=============================================================================================
Activity 里面使用下载类
String UrlTxt = new String("http://192.168.1.111/test.mp3");
HttpDownloader downloader = new HttpDownloader();
HttpCallbackListener httpcallback = new HttpCallbackListener() {
@Override
public void onFinish(String response) {
Log.d("下载二进制文件完成,结果=>" , response);
}
@Override
public void onError(Exception e) {
// TODO Auto-generated method stub
Log.d("下载二进制文件错误" , e.getMessage());
}
};
downloader.downFile(UrlTxt, "test/", "newname.mp3", httpcallback);