android中使用http请求下载文件,并且将文件保存到SDcard中

时间:2022-08-24 14:57:32

使用http协议下载网络文件,HttpDownloader .java


public class HttpDownloader {
private URL url = null;




/*根据url下载文本文件
* */
public String download(String urlString){
StringBuffer sb = new StringBuffer();
BufferedReader buffer = null;
String line = null;
try{
//创建URL对象
url = new URL(urlString);

//创建http连接
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();

/*使用IO流读取数据
getInputStream()  return 字节流
InputStreamReader()   return 字符流*/
buffer = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

while((line = buffer.readLine()) != null)
{
sb.append(line);
}

}catch(Exception e){
e.printStackTrace();
}finally{
try{
//close buffer
buffer.close();
}catch(Exception e){
e.printStackTrace();
}
}

return sb.toString();
}


//下载任意格式的文件并且保存到SD card
/* return:
* 1  表示文件已经存在
* -1 保存出错
* 0 表示成功

* param:
* urlStr 下载的原链接
* fileName  保存在SDcard中的名字
* path  保存在SDcard下的目录
*/
public int downloadFile(String urlStr, String path, String fileName){
InputStream inputStream = null;
try{
Filesys filesys = new Filesys();
if(filesys.isFileExist(path + fileName)){
return 1;
}else{
inputStream = getInputStreamFromUrlStr(urlStr);
File resultFile = filesys.write2SDFromInput(path, fileName, inputStream);
if(resultFile == null)
return -1;
}

}catch(Exception e){
e.printStackTrace();
return -1;
}finally{
try{
inputStream.close();
}catch(Exception e){
e.printStackTrace();
}
}
return 0;
}

public InputStream getInputStreamFromUrlStr(String urlStr) throws IOException{

InputStream input = null;
//创建URL对象
URL url = new URL(urlStr);

//创建http连接
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();

//获取输入流
input = urlConnection.getInputStream();
return input;
}

}

将文件获得的文件流保存到SDcard中Filesys.java


public class Filesys {
private String SDPATH = null;


public String getSDPath(){
return SDPATH;
}

//构造函数
public Filesys(){
//get  外部设备的路径
SDPATH = Environment.getExternalStorageDirectory() + "/";
}


//在SDCARD中创建文件
public File createSDFile(String fileName) throws IOException{
//创建一个FILE 对象
File file = new File(SDPATH + fileName);
file.createNewFile();
return file;
}


//在SDCARD中创建目录
public File createSDDir(String dirName){

File dir = new File(SDPATH + dirName);
dir.mkdir();
Log.i("filesys","create :" + SDPATH + dirName);
return dir;
}

//判断SD卡上的文件是否存在
public boolean isFileExist(String fileName){

File file = new File(SDPATH + fileName);
Log.i("filesys","isFileExist :" + SDPATH + fileName);

return file.exists();
}

//将inputStream中的数据写入到SD卡中
public File write2SDFromInput(String path, String fileName,InputStream input){
File file = null;
OutputStream output = null;
int len = -1;
try{

createSDDir(path);
file = createSDFile(path + fileName);
output = new FileOutputStream(file);

byte buffer[] = new byte[4 * 1024];
while((len = input.read(buffer)) != -1){
//output.write(buffer);  //使用此函数会导致下载的文件偏大
output.write(buffer, 0, len);
}
input.close();
//清空缓存
output.flush();

}catch(Exception e){
e.printStackTrace();
}finally{
try{
output.close();
}catch(Exception e){
e.printStackTrace();
}
}


return file;
}



}


注意:在android4.0以后的版本,在主线程中不能请求http请求,怕阻塞主线程,可以使用如下方法,创建一个子线程来完成http请求工作

// Android 4.0 之后不能在主线程中请求HTTP请求,创建子线程来下载
new Thread(new Runnable(){
                @Override
                public void run() {
                HttpDownloader downloader = new HttpDownloader();
        int result = downloader.downloadFile("http://172.16.6.162/test.mp3", "testDownload/", "test1.mp3"); 
        System.out.println(result);
                }
            }).start();



还需要在manifest中设置访问网络和writeSDcard的权限