我正在尝试从网络服务器获取图像,如下所示:
@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 格式。