2013-07-18 30 views
1

我想從這樣的網絡服務器獲取圖像:的Android BitmapFactory不能解碼的InputStream

@Override 
    protected InputStream doInBackground(String... strings) { 
     InputStream stream = null; 
     try { 
      URL url = new URL(strings[0]); 
      HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
      connection.connect(); 
      stream = connection.getInputStream(); 
      connection.disconnect(); 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } finally { 
      return stream; 
     } 
    } 

    @Override 
    protected void onPostExecute(InputStream stream) { 
     try { 
      BufferedInputStream buf = new BufferedInputStream(stream); 
      Bitmap avatar = BitmapFactory.decodeStream(buf); 
      user.avatar = avatar; 
      if (user.avatar != null) 
       imgAvatar.setImageBitmap(user.avatar); 
      buf.close(); 
      stream.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

但我Bitmap avatar爲空。我一直在通過調試器查看收到的InputStream,它包含正確的url,並且它有字段httpEngine/responseBodyIn/bytesRemaining,它保存的字節數等於圖像大小。圖像的格式爲.png。

+0

試試這個http://stackoverflow.com/a/5941493/1443981 – Aswin

+0

面臨位ISSU時,我總是先看看這裏的https: //github.com/nostra13/Android-Universal-Image-Loader –

回答

0

好吧,我解決了它使用的不是HttpURLConnection類的Apache的HttpClient:

protected InputStream doInBackground(String... strings) { 
     HttpResponse response = null; 
     InputStream instream = null; 

     try { 
      HttpClient client = new DefaultHttpClient(); 
      HttpGet request = new HttpGet(new URL(strings[0]).toURI()); 
      response = client.execute(request); 
      if (response.getStatusLine().getStatusCode() != 200) { 
       return null; 
      } 
      BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(response.getEntity()); 
      instream = bufHttpEntity.getContent(); 

      return instream; 
     } 
     catch (Exception ex) { 
      return null; 
     } 
     finally { 
      if (instream != null) { 
       try { 
        instream.close(); 
       } catch (IOException e) { 
       } 
      } 
     } 
    } 

    @Override 
    protected void onPostExecute(InputStream stream) { 
     Bitmap avatar = BitmapFactory.decodeStream(stream); 
     if (avatar != null) { 
      user.avatar = avatar; 
      imgAvatar.setImageBitmap(avatar); 
     } 
    }