安装包下载源码

package com.example.test2;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.util.Log;

public class downloader {

public static void connet(String path,String savePath){
	try { 
	    URL url = new URL(path); 
	    HttpURLConnection connection = (HttpURLConnection) url .openConnection(); 
	    connection.setConnectTimeout(10 * 1000); //超时时间
	    connection.connect();  //连接
	    if (connection.getResponseCode() == 200) { //返回的响应码200,是成功.
	        File file = new File(savePath);   //这里我是手写了。建议大家用自带的类
	        file.createNewFile(); 
	        InputStream inputStream = connection.getInputStream(); 
	        ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); //缓存
	        byte[] buffer = new byte[1024 * 10]; 
	        while (true) { 
	           int len = inputStream.read(buffer); 
	           Log.i("qiyi","下载长度:"+len);
	         //  publishProgress(len); 
	            if (len == -1) { 
	                break;  //读取完
	            } 
	           arrayOutputStream.write(buffer, 0, len);  //写入
	        } 
	        arrayOutputStream.close(); 
	        inputStream.close(); 

	        byte[] data = arrayOutputStream.toByteArray(); 
	        FileOutputStream fileOutputStream = new FileOutputStream(file); 
	        fileOutputStream.write(data); //记得关闭输入流
	        fileOutputStream.close(); 
	    } 

	} catch (MalformedURLException e) { 
         e.printStackTrace(); 
	} catch (IOException e) { 
	    e.printStackTrace(); 
	} 
}
}

  

		final String savePath=Environment.getExternalStorageDirectory().getAbsolutePath() + "/zhushou.apk";// filePath:/sdcard/
		Log.i("qiyi", savePath);
		new Thread(){
			@Override
			public void run() {
				downloader.connet("http://gdown.baidu.com/data/wisegame/3c21fa92f977f524/91zhushou_86.apk", savePath);	
			}	
		}.start();
					

  

posted on 2014-05-15 15:47  clarenceV1  阅读(305)  评论(0编辑  收藏  举报

导航