一、用HttpClient下图片:
protected Bitmap doInBackground(String... params) {
// 完成对图片下载的功能
Bitmap bitmap=null;
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
InputStream inputStream=null;
try {
HttpClient httpClient=new DefaultHttpClient();
HttpGet httpGet=new HttpGet(params[0]);
HttpResponse httpResponse=httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode()==200){
inputStream=httpResponse.getEntity().getContent();
//先要获得文件的总长度
long file_length=httpResponse.getEntity().getContentLength();
int len=0;
byte[] data=new byte[1024];//读取
int total_length=0;
while((len=inputStream.read(data))!=-1){
System.out.println(total_length);
total_length += len;
int value=(int) ((total_length / (float) file_length) * 100);
publishProgress(value);//把刻度发布出去
outputStream.write(data, 0, len);//写入
}
byte[] result=outputStream.toByteArray();//声明字节数组
bitmap=BitmapFactory.decodeByteArray(result, 0, result. length);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bitmap;
}
二、用URLConnection下载图片
public void run (){
URL urll;
try {
urll = new URL("http://www.91ri.org/9408.html");
HttpURLConnection conn = (HttpURLConnection) urll.openConnection();
conn.setConnectTimeout(5000);
//获取到文件的大小
int total_length = conn.getContentLength();
//pd.setMax(conn.getContentLength());
InputStream is = conn.getInputStream();
File file = new File(Environment.getExternalStorageDirectory(), "aupdata.html");
FileOutputStream fos = new FileOutputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
int len ;
int total=0;
while((len = bis.read(buffer)) != -1){
fos.write(buffer, 0, len);
total = total + len ;
System.out.println(total);
Thread.sleep(1000);
progress_num = (100*total)/total_length ;
System.out.println("pro" + progress_num + "gg" + total_length);
//progress_num = total;
progress_handler.sendEmptyMessage(0x123);
//pd.setProgress(total);
}
fos.close();
bis.close();
is.close();
二者的比较,请看以下链接
http://blog.youkuaiyun.com/zealot_2002/article/details/8250268