get请求网络图片

public static Bitmap httpGETImage(String string) {
        try {
            //设置URL
            URL url = new URL(string);
            //得到HttpURLConnection
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            //连接超时时间
            connection.setConnectTimeout(5000);
            //读取超时
            connection.setReadTimeout(5000);
            //获取请求码 一般情况下200是成功
            int code = connection.getResponseCode();
            //判断请求码是否 请求成功
            if (code == HttpURLConnection.HTTP_OK) {
                //得到数据
                InputStream stream = connection.getInputStream();
                // 如果是图片
                Bitmap bitmap = BitmapFactory.decodeStream(stream);

                return bitmap;
            }
            connection.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

猜你喜欢

转载自blog.csdn.net/qq_43413640/article/details/85332292