android中的httpdown的工具類

package com.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;


/**
 * 封裝了一些下載文件的類,可以在Activity文件中直接調用
 * @author zl 
 */
public class HttpDownLoad {

 private URL url = null;
 
 /**
  * 根據URL得到一個輸入流
  * @param urlStr
  * @return
  * @throws MalformedURLException
  * @throws IOException
  */
 public InputStream getInputStreamFromUrl (String urlStr) throws MalformedURLException,IOException{
  url = new URL(urlStr);
  HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
  InputStream inputStream = urlConn.getInputStream();
  return inputStream;
 }
 
 /**
  * 根據URL下載文件,前提是這個文件當中的內容是文本,函數的返回值就是文件中的內容
  * 1.創建一個URL對象
  * 2.通過URL對象,創建一個HttpURLConnection對象
  * 3.得到InputStream
  * 4.從InputStream中讀取數據
  */

 public String downloadText(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()));
   //使用循環將讀取的一行一行的數據存入到StringBuffer對象中
   while((line = buffer.readLine()) != null){
    sb.append(line);
   }
  } catch (Exception e) {
   // TODO: handle exception
   e.printStackTrace();
  }finally{
   try {
    buffer.close();
    
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  return sb.toString();
 }
 
 /**
  * 根據URL下載文件,這個文件可以是其他文件,返回這個文件下載是否成功
  * @param urlStr --地址
  * @param path --存儲路徑
  * @param fileName --存儲文件名
  * @param againDown --布爾值判斷否在文件已存在時下載
  * @return
  * 返回值:-1-->下載失敗,0-->下載成功,1-->文件存在
  */
 public int downFile(String urlStr,String path,String fileName,Boolean againDown){
  //生成一個InputStream對象
  InputStream inputStream = null;
  //創建FileUtils對象,用於判斷要下載的文件是否存在
  FileUtils fileUtils = new FileUtils();
  boolean isFileUtils = fileUtils.isFileExist(path+fileName);
  try {
   //文件存在且不重新下載時,返回1
   if(isFileUtils && againDown == false){
    return 1;
   }
   //文件存在且要重新下載時或文件不存在時下載
   else if((isFileUtils && againDown == true) || isFileUtils == false){
    //根據URL輸入流下載
    inputStream = getInputStreamFromUrl(urlStr);
    //調用存入SD卡的方法,並返回存入結果
    File resultFile = fileUtils.write2SDFromInput(path, fileName, inputStream);
    //存入爲空時,返回-1
    if(resultFile == null){
     return -1;
    }
   }
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   //出現異常時,返回-1
   return -1;
  } finally{
   try {
    inputStream.close();
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  //都正常時,返回0
  return 0;
 }
 
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章