您的位置:首页 > 理论基础 > 计算机网络

Android利用Http下载文件

2015-08-21 17:18 585 查看
Android利用Http下载文件

一、场景

   下载存文本文件和下载如mp3等大容量的文件

界面



二、代码编写

 1.AndroidMainfest.xml中配置

主要是解决网络权限和写SDCard的权限

 

 

Java代码  


<?xml version="1.0" encoding="utf-8"?>  

<manifest xmlns:android="http://schemas.android.com/apk/res/android"  

    package="linys.download" android:versionCode="1" android:versionName="1.0">  

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

  

    <application android:icon="@drawable/icon" android:label="@string/app_name">  

        <activity android:name=".Download" 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>  

    <!-- 访问网络和操作SD卡 加入的两个权限配置 -->  

        <uses-permission android:name="android.permission.INTERNET" />  

        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  

</manifest>  

 

2.Activity编写

 利用Http协议下载文件并存储到SDCard

    1.创建一个URL对象

    2.通过URL对象,创建一个HttpURLConnection对象

    3.得到InputStream

    4.从InputStream当中读取数据

    存到SDCard

    1.取得SDCard路径

    2.利用读取大文件的IO读法,读取文件

Java代码  


package linys.download;  

  

import java.io.BufferedReader;  

import java.io.File;  

import java.io.FileOutputStream;  

import java.io.IOException;  

import java.io.InputStream;  

import java.io.InputStreamReader;  

import java.io.OutputStream;  

import java.net.HttpURLConnection;  

import java.net.MalformedURLException;  

import java.net.URL;  

  

import android.app.Activity;  

import android.os.Bundle;  

import android.os.Environment;  

import android.view.View;  

import android.view.View.OnClickListener;  

import android.widget.Button;  

/** 

 *  

 * @Project: Android_MyDownload 

 * @Desciption: 利用Http协议下载文件并存储到SDCard 

    1.创建一个URL对象 

    2.通过URL对象,创建一个HttpURLConnection对象 

    3.得到InputStream 

    4.从InputStream当中读取数据 

    存到SDCard 

    1.取得SDCard路径 

    2.利用读取大文件的IO读法,读取文件 

 *  

 * @Author: LinYiSong 

 * @Date: 2011-3-25~2011-3-25 

 */  

public class MyDownload extends Activity {  

      

    private Button downFileBtn;  

    private Button downMP3Btn;  

    /** Called when the activity is first created. */  

    @Override  

    public void onCreate(Bundle savedInstanceState) {  

        super.onCreate(savedInstanceState);  

        setContentView(R.layout.main);  

          

        downFileBtn=(Button)this.findViewById(R.id.downFile);  

        downMP3Btn=(Button)this.findViewById(R.id.downMP3);  

          

        downFileBtn.setOnClickListener(new DownFileClickListener());  

        downMP3Btn.setOnClickListener(new DownMP3ClickListener());  

    }  

      

    /** 

     *  

     * @Project: Android_MyDownload 

     * @Desciption: 只能读取文本文件,读取mp3文件会出现内存溢出现象 

     * @Author: LinYiSong 

     * @Date: 2011-3-25~2011-3-25 

     */  

    class DownFileClickListener implements OnClickListener{  

        @Override  

        public void onClick(View v) {  

            String urlStr="http://172.17.54.91:8080/download/down.txt";  

            try {  

                /* 

                 * 通过URL取得HttpURLConnection 

                 * 要网络连接成功,需在AndroidMainfest.xml中进行权限配置 

                 * <uses-permission android:name="android.permission.INTERNET" /> 

                 */  

                URL url=new URL(urlStr);  

                HttpURLConnection conn=(HttpURLConnection)url.openConnection();  

                //取得inputStream,并进行读取  

                InputStream input=conn.getInputStream();  

                BufferedReader in=new BufferedReader(new InputStreamReader(input));  

                String line=null;  

                StringBuffer sb=new StringBuffer();  

                while((line=in.readLine())!=null){  

                    sb.append(line);  

                }  

                System.out.println(sb.toString());  

                  

            } catch (MalformedURLException e) {  

                e.printStackTrace();  

            } catch (IOException e) {  

                e.printStackTrace();  

            }  

        }  

    }  

    /** 

     *  

     * @Project: Android_MyDownload 

     * @Desciption: 读取任意文件,并将文件保存到手机SDCard 

     * @Author: LinYiSong 

     * @Date: 2011-3-25~2011-3-25 

     */  

    class DownMP3ClickListener implements OnClickListener{  

  

        @Override  

        public void onClick(View v) {  

            String urlStr="http://172.17.54.91:8080/download/1.mp3";  

            String path="file";  

            String fileName="2.mp3";  

            OutputStream output=null;  

            try {  

                /* 

                 * 通过URL取得HttpURLConnection 

                 * 要网络连接成功,需在AndroidMainfest.xml中进行权限配置 

                 * <uses-permission android:name="android.permission.INTERNET" /> 

                 */  

                URL url=new URL(urlStr);  

                HttpURLConnection conn=(HttpURLConnection)url.openConnection();  

                //取得inputStream,并将流中的信息写入SDCard  

                  

                /* 

                 * 写前准备 

                 * 1.在AndroidMainfest.xml中进行权限配置 

                 * <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

                 * 取得写入SDCard的权限 

                 * 2.取得SDCard的路径: Environment.getExternalStorageDirectory() 

                 * 3.检查要保存的文件上是否已经存在 

                 * 4.不存在,新建文件夹,新建文件 

                 * 5.将input流中的信息写入SDCard 

                 * 6.关闭流 

                 */  

                String SDCard=Environment.getExternalStorageDirectory()+"";  

                String pathName=SDCard+"/"+path+"/"+fileName;//文件存储路径  

                  

                File file=new File(pathName);  

                InputStream input=conn.getInputStream();  

                if(file.exists()){  

                    System.out.println("exits");  

                    return;  

                }else{  

                    String dir=SDCard+"/"+path;  

                    new File(dir).mkdir();//新建文件夹  

                    file.createNewFile();//新建文件  

                    output=new FileOutputStream(file);  

                    //读取大文件  

                    byte[] buffer=new byte[4*1024];  

                    while(input.read(buffer)!=-1){  

                        output.write(buffer);  

                    }  

                    output.flush();  

                }  

            } catch (MalformedURLException e) {  

                e.printStackTrace();  

            } catch (IOException e) {  

                e.printStackTrace();  

            }finally{  

                try {  

                        output.close();  

                        System.out.println("success");  

                    } catch (IOException e) {  

                        System.out.println("fail");  

                        e.printStackTrace();  

                    }  

            }  

        }  

          

    }  

}  

 

 

 

Android_MyDownload.rar (45.8 KB)
下载次数: 341
Android_Download.rar (50.3 KB)
下载次数: 439
查看图片附件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: