http的哪种方法最适合android?

时间:2012-01-19 09:35:23

标签: android multithreading http connection

我有2种方法从互联网下载图片,结果是输入流。 但其中一个会使下载图像失败,我不知道为什么, 这是有错误的代码:

            HttpGet get = new HttpGet(imageName);
            HttpResponse response = (HttpResponse) httpClient.execute(get);
            HttpEntity entity = response.getEntity();
            BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity); 
            InputStream is = bufHttpEntity.getContent();

这是我正在使用的另一个:

        URL imageUrl = new URL(imageName);
        conn = (HttpURLConnection) imageUrl
                .openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setInstanceFollowRedirects(true);
        InputStream is = conn.getInputStream();

我很奇怪是否有人可以告诉我 1.为什么我使用方法1来获取一个无法显示图片的inputstram 2.我见过有人说使用httpclient,不要使用连接。我不知道原因??连接更糟糕的是http客户端??

我在多线程环境中使用,方法二工作正常,但方法一不能。

1 个答案:

答案 0 :(得分:0)

public static Bitmap getimage(String imageUrl) {

        Log.i("imageurl", imageUrl);
        Bitmap bitmap = null;
        BufferedInputStream bis = null;
        InputStream is = null;

        try {
            String url = imageUrl;
            URL myUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();

            conn.setDoInput(true);
            conn.connect();
            if (conn.getResponseCode() != 404) {
                is = conn.getInputStream();
                bis = new BufferedInputStream(is, 8192);
                bitmap = BitmapFactory.decodeStream(bis);

            }
            conn.disconnect();

        }catch (Exception e) {
             Log.e("getImageData", e.toString());
             return bitmap;
        }
        finally{
            if (bis != null) 
            {
                try{
                    bis.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) 
            {
                try {
                    is.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
         return bitmap;
    }