018使用Http协议从网络上下载文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Birdmotianlun/article/details/50350013

这里写图片描述
这里写图片描述
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>

猜你喜欢

转载自blog.csdn.net/Birdmotianlun/article/details/50350013