Android 通过Http请求网络获取图片资源

    在日常的编写Android软件的过程中,避免不了使用网络请求,但是发http请求是不能在主线程里面发,否则就会出现android.os.NetworkOnMainThreadException的异常,所以必须要放到子线程中处理。步骤如下:

       1、将想要请求的图片地址转换成URL类

  2、通过openConnection来建立连接

  3、在编程的时候避免让用户等,设置网络连接的超时时间,读取时间

  4、设置请求网络的类型(GET或者POST)

  5、提交网络请求

  6、接受返回码,通过返回码判断网络是否请求成功

注意:任何网络请求必须加上网络权限 <uses-permission android:name="android.permission.INTERNET"/>

下面是代码:


    /**
     * 根据传入url获取到它的图片
     */
    private void getBitmap(final String imgUrl) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL bitmapUrl = new URL(imgUrl);
                    connection = (HttpURLConnection) bitmapUrl.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(5000);
                    connection.setReadTimeout(5000);
                    //通过返回码判断网络是否请求成功
                    if (connection.getResponseCode() == 200) {
                        InputStream inputStream = connection.getInputStream();
                        Bitmap shareBitmap = BitmapFactory.decodeStream(inputStream);
                        Message message = wxHandler.obtainMessage();
                        message.what = 0;
                        message.obj = shareBitmap;
                        wxHandler.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

这里还需要一个Handler来在主线程中设置ImageView的图片

    @SuppressLint("HandlerLeak")
    private Handler wxHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Bitmap wxShareBitmap = (Bitmap) msg.obj;
                    break;
            }
        }
    };

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值