Android开发学习—— 下载网络图片

现在几乎所有的应用都在使用网络来达到浏览的目的。对于特定领域 使用xnpp协议 像即时通讯软件。但大多数还是使用HTTP协议来交互。

网络图片查看器

HTTP协议 下载网络 图片

<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="com.example.he.MainActivity" >

    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="下载图片"
        android:onClick="click"
        />
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       android:id="@+id/iv"
         />

</RelativeLayout>
public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void click(View v) throws IOException{
        //确定网址,此网址是图片的地址
        String imgurl="http://127.0.0.1:8080/dd.jpg";
        
        try {
            //把网址封装为url对象
            URL url = new URL(imgurl);
            //获取客户端和服务器端的连接对象,此时还没有建立连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
            //对连接对象进行初始化,设置请求方法
            try {
                conn.setRequestMethod("GET");
            } catch (ProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            conn.setConnectTimeout(5000);//5s超时
            conn.setReadTimeout(5000);//读取超时,网址是对的,流没有正确返回。
            //发送请求,与服务器建立连接
            conn.connect();
            //请求成功,服务器会返回一个流
            if(conn.getResponseCode()==200){
                InputStream is = conn.getInputStream();
                Bitmap bm = BitmapFactory.decodeStream(is);//读取流里的数据并构造位图对象
                ImageView iv = (ImageView) findViewById(R.id.iv);    
                iv.setImageBitmap(bm);
                
            }
            else{
                Toast.makeText(this, "请求失败", 0).show();
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

 * 添加权限

原文地址:https://www.cnblogs.com/mengxiao/p/6183748.html