Android - 无法从http加载图片

时间:2013-10-28 19:47:36

标签: android http url

我需要从http加载图片,我正在使用此代码:

                        Bitmap bitmap;                        
                        InputStream is = null;
                        try {
                            is = (InputStream) new URL("www.TESTWEBSITE.com/TEST.JPG").getContent();
                        } catch (MalformedURLException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }



                        bitmap = BitmapFactory.decodeStream(is);

但是位图仍为空..请帮忙吗?

1 个答案:

答案 0 :(得分:1)

更新:这是执行您想要的完整快照:

        Bitmap bitmap = null;
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL("www.TESTWEBSITE.com/TEST.JPG");
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream is = urlConnection.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }

请确保在UI线程中运行它,例如在AsyncTask中,正如其他人所评论的那样。您可以在主线程中尝试用于实验目的,但要为ANR做好准备。