2012-01-19 7 views
1

私はインターネットから画像をダウンロードする方法が2つあり、結果は入力ストリームです。httpのどの方法がアンドロイドに最適ですか?

 URL imageUrl = new URL(imageName); 
     conn = (HttpURLConnection) imageUrl 
       .openConnection(); 
     conn.setConnectTimeout(30000); 
     conn.setReadTimeout(30000); 
     conn.setInstanceFollowRedirects(true); 
     InputStream is = conn.getInputStream(); 
:これは私が使用している別の1である

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

: が、これの一つは、ダウンロード画像が失敗になります、私はなぜ知らない、ここで バグを持っているのコードです

私はどちらかが私に教えてくれるのだろうかと思っています 1.なぜ私は方法1を使用して画像を表示することができません 2.私は、httpclientを使用して接続を使用しないと言ういくつかの人を見ました。私は理由を知らない?接続は悪いですhttpクライアント?

私はマルチスレッド環境で使用していますが、方法2は正常ですが、方法1は使用できません。

答えて

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; 
    } 
+0

bufferedinputstreamの方が良いですか? – rex

関連する問題