1. 程式人生 > >018使用Http協議從網路上下載檔案

018使用Http協議從網路上下載檔案

這裡寫圖片描述
這裡寫圖片描述
1: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft
="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" >
<Button android:id="@+id/downloadText" android:layout_width="wrap_content" android:layout_height
="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginTop="14dp" android:text="下載文字檔案" />
<Button android:id="@+id/downloadMp3" android:layout_width="wrap_content" android:layout_height
="wrap_content" android:layout_alignLeft="@+id/downloadText" android:layout_below="@+id/downloadText" android:layout_marginTop="16dp" android:text="下載歌詞檔案" />
</RelativeLayout>

2: HttpDownloader.java

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


/**
 * 下載文字檔案
 * 根據URL下載檔案,前提是這個檔案當中的內容是文字,函式的返回值就是檔案當中的內容
 * 1.建立一個URL物件
 * 2.通過URL物件,建立一個HttpURLConnection物件
 * 3.得到InputStram
 * 4.從InputStream當中讀取資料
 */

public String download(String urlString){
    StringBuffer sb=new StringBuffer();
    String line=null;
    BufferedReader buffer=null;
    try {
        //建立URL物件
        url=new URL(urlString);
        //建立HTTP連線
        HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();
        buffer=new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
        //讀取多行資料,一行一行讀取
        while((line=buffer.readLine())!=null){
            sb.append(line);//新增資料到每一行的後面
        }

    } catch (Exception e) {
        // TODO: handle exception
        System.out.println("--------------------------");
    }
    return sb.toString();

}

/**
 * 下載mp3檔案到sd卡,可以下載任意 格式檔案
 * 訪問sdCard方法
 * 1 得到當前裝置sd卡的目錄
 * Envoronment.getExternalStorageDirectory()
 * 2 許可權
 * android.permission.WRITE_EXTERNAL_STORAGE
 */
//downFile(連線,存放目錄,寫入目錄)
/*
 * 該函式返回整形  
 *  -1:代表下載檔案出錯
 *  0:代表下載檔案成功 
 *  1:代表檔案已經存在
 */
//次方法可以下載任意格式檔案
public int downFile(String urlStr,String path,String fileName){
    InputStream inputStream=null;
    try {
        FileUtils fileUtils = new FileUtils();

        if (fileUtils.isFileExist(path + fileName)) {
            return 1;//返回1說明檔案已經存在
        } else {
            inputStream = getInputStreamFromUrl(urlStr);
            File resultFile = fileUtils.writeSDFromInput(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;//現在成功
}
/**
 * 根據URL得到輸入流
 */
public InputStream getInputStreamFromUrl(String urlStr)
        throws MalformedURLException, IOException {
    url = new URL(urlStr);
    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
    InputStream inputStream = urlConn.getInputStream();
    return inputStream;
}

}

3:工具包檔案FileUtils.java

/**
 * 下載mp3檔案到sd卡,可以下載任意 格式檔案
 * 
 * 訪問sdCard方法
 * 1 得到當前裝置sd卡的目錄
 * Envoronment.getExternalStorageDirectory()
 * 2 許可權
 * android.permission.WRITE_EXTERNAL_STORAGE
 */
package com.lun.utils;

import java.io.*;//匯入
import android.os.Environment;//匯入

public class FileUtils {

    private String SDPATH;

    public String getSDPATH() {
        return SDPATH;
    }

    public FileUtils() {
        // 得到當前外部儲存裝置目錄,後面加一個”/“方便寫檔名
        SDPATH = Environment.getExternalStorageDirectory() + "/";
    }


    /*
     * 在sd卡建立檔案
     */
    public File createSDFile(String fileName) throws IOException {
        File file = new File(SDPATH + fileName);
        file.createNewFile();
        return file;

    }

    /*
     * 在SD卡上建立目錄
     */
    public File createSDDir(String dirName) {
        File dir = new File(SDPATH + dirName);
        dir.mkdirs();
        return dir;

    }

    /*
     * 判斷SD卡上檔案是否存在
     */
    public boolean isFileExist(String fileName) {
        File file = new File(SDPATH + fileName);
        return file.exists();

    }

    /*
     * 將一個inputStream裡面資料寫入到sd卡 InputStream讀取資料 OutputStream寫入資料
     */
    public File writeSDFromInput(String path, String fileName, InputStream input) {
        File file = null;
        OutputStream output = null;
        try {
            createSDDir(path);// 建立目錄
            file = createSDFile(SDPATH + fileName);// 建立檔名
            output = new FileOutputStream(file);// 寫入檔案流
            byte buffer[] = new byte[4 * 1024];// 每次寫入大小
            while ((input.read(buffer)) != -1) {
                output.write(buffer);// 寫入檔案
            }
            output.flush();//清空快取

        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            try {
                output.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;

    }
}

4:MainActivity.java

/*
 * 1 使用HTTP協議下載檔案
 * 2 將下載檔案儲存到sd卡
 * 
 * 下載檔案步驟:
 * 1 建立一個HttpURLConnection物件
 * HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();
 * 2 獲取InputStream()物件
 * urlConn.getInputStream()
 * 3 新增訪問網路許可權
 * android.permission.INTERNET
 */
package com.example.android018;

import com.lun.utils.HttpDownloader;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
    private Button butDownText;
    private Button butDownMp3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        butDownText = (Button) findViewById(R.id.downloadText);
        butDownMp3 = (Button) findViewById(R.id.downloadMp3);
        butDownText.setOnClickListener(new buDownTextListener());
        butDownText.setOnClickListener(new buDownMp3Listener());

    }

    class buDownTextListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            // TODO 自動生成的方法存根
            HttpDownloader httpDown = new HttpDownloader();
            String txt = httpDown.download("http://aaaa/");// 下載文字檔案,地址可以是網路地址
            System.out.println(txt);

        }

    }

    class buDownMp3Listener implements OnClickListener {

        @Override
        public void onClick(View v) {
            // TODO 自動生成的方法存根
            HttpDownloader httpDown = new HttpDownloader();
            // 下載任意格式的網路檔案
            int result = httpDown.downFile(
                    "http://192.168.1.107:8080/voa1500/a1.mp3", "voa/",
                    "a1.mp3");
            System.out.println(result);

        }

    }

}

5:許可權配置

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android018"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <uses-permission android:name="android.permission.INTERNET" />
    <!--
 在2.x的版本中,android.permission.WRITE_EXTERNAL_STORAGE確實是用來使得sd卡獲得寫的許可權。
 而在4.0開發的原始碼當中,由於有了內外接sd卡的區分,
android.permission.WRITE_EXTERNAL_STORAGE的許可權用來設定了內建sd卡的寫許可權。
android.permission.WRITE_MEDIA_STORAGE設定外接sd卡許可權 。
    -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.android018.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>