一般的http下载图片

来源:互联网 发布:万网已备案未注册域名 编辑:程序博客网 时间:2024/06/04 19:12


<LinearLayout 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:orientation="vertical"
    android:background="#66ff0000"
    tools:context=".MainActivity" >

    <EditText
        android:text="http://www.baidu.com/img/bd_logo1.png"
        android:id="@+id/mEtUrlPath"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入网络图片的路径" />

    <Button
        android:onClick="click"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="查看" />

    <ImageView
        android:id="@+id/mIvShow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>


package com.example.sqldemo1;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
 
 private static final int MSG_NEW_PIC = 2;
 private static final int MSG_CACHE_PIC = 1;
 private static final int ERROR = 3;
 private static final int EXCEPTION = 4;
 private EditText mEtUrlPath;
 private ImageView mIvShow;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  mEtUrlPath = (EditText) findViewById(R.id.mEtUrlPath);
  mIvShow = (ImageView) findViewById(R.id.mIvShow);
 }
 
 //在主线程里面声明消息处理器handler
 private Handler handler = new Handler(){
  public void handleMessage(Message msg) {
   switch (msg.what) {
   case MSG_CACHE_PIC:
    //处理消息,运行在主线程
    Bitmap bitmap = (Bitmap) msg.obj;
    mIvShow.setImageBitmap(bitmap);
    System.out.println("(不用下载)缓存图片");
    break;

   case MSG_NEW_PIC:
    Bitmap bitmap2 = (Bitmap) msg.obj;
    mIvShow.setImageBitmap(bitmap2);
    System.out.println("新下载(不用下载)缓存图片");
    break;
    
   case ERROR:
    Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
    break;
    
   case EXCEPTION:
    Toast.makeText(MainActivity.this, "发生异常,请求失败", Toast.LENGTH_SHORT).show();
    break;
   }
   super.handleMessage(msg);
  }
 };
 
 public void click(View view) {
  // TODO Auto-generated method stub
  final String path = mEtUrlPath.getText().toString().trim();
  if (TextUtils.isEmpty(path)) {
   Toast.makeText(MainActivity.this, "图片路径不能为空", Toast.LENGTH_SHORT).show();
   return;
  }
  new Thread(){
   public void run(){
    getImage(path);
   };
  }.start();
 }
 
 private void getImage(String path){
  File file = new File(getCacheDir(), Base64.encodeToString(path.getBytes(), Base64.DEFAULT));
  if (file.exists() && file.length() > 0) {//判断文件名是否存在
   System.out.println("图片存在,拿缓存");
   Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
   Message msg = new Message();//声明消息
   msg.what = MSG_CACHE_PIC;
   msg.obj = bitmap;//设置数据
   handler.sendMessage(msg);//让handler帮我们发送数据
  }else{
   System.out.println("图片不存在,获取数据生成缓存");
   try{
    //1.声明访问的路径,url网络资源htp rtsp
    URL url = new URL(path);
    //2.通过路径得到一个连接http的连接
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    //3.判断服务器给我们返回的状态的状态信息。
    //200成功302从定向 404资源没找到 5xx服务器内部错误
    int code = conn.getResponseCode();
    if (code == 200) {
     InputStream is = conn.getInputStream(); //png的图片
     FileOutputStream fos = new FileOutputStream(file);
     byte[] buffer = new byte[1024];
     int len = -1;
     while ((len = is.read(buffer)) != -1) {
      fos.write(buffer, 0, len);
     }
     is.close();
     fos.close();
     Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
     //更新ui,不能写在子线程里
     Message msg = new Message();
     msg.obj = bitmap;
     msg.what = MSG_NEW_PIC;
     handler.sendMessage(msg);
//     iv.setImageBitmap(bitmap);
    }else{
     //请求失败
     //土司更新ui, 不能写在子线程
//     Toast.makeText(this, "请求失败", 0).show();
     Message msg = new Message();
     msg.what = ERROR;
     handler.sendMessage(msg);
    }
   } catch (Exception e) {
    e.printStackTrace();
    //土司不能写在子线程
//    Toast.makeText(this, "发生异常,请求失败", 0).show();
    Message msg = new Message();
    msg.what = EXCEPTION;
    handler.sendMessage(msg);
   }
  }
 }
}

0 0
原创粉丝点击