1

我正在尝试从网络服务器获取图像,如下所示:

@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 格式。

4

1 回答 1

0

好的,我使用 Apache HttpClient 而不是 HttpUrlConnection 解决了它:

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);
        }
    }
于 2013-07-18T12:22:11.390 回答