我正试图从网络服务器获取图像:
@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 :(得分: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);
}
}