【发布时间】:2016-05-26 12:08:32
【问题描述】:
我尝试从 url 加载图像并显示 imageview。我编写的代码女巫可以下载图像并显示它。但现在我想下载 facebook 用户图像并显示它。我知道如何检查 facebook 用户图像“像这样 http://graph.facebook.com/userid /picture?width=80&height=80 当我运行程序时,我有 RuntimeException 这是我的来源
private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
// Sets the Bitmap returned by doInBackground
@Override
protected void onPostExecute(Bitmap result) {
user_img.setImageBitmap(result);
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
new GetXMLTask().execute((new String[] { URL }));
如果我的网址是 http://mywebsite./pic.jpg,那么程序运行完美,但我想显示 facebook 用户图片
【问题讨论】:
-
什么是 RuntimeException?
http://graph.facebook.com/user id /picture?width=80&height=80将发回 302 重定向,因此您需要确保遵循该重定向。 -
RuntimeException: 执行doInBackground时出错
-
我的猜测是 getHttpConnection 返回 null 因为 GET 请求返回 302 而不是 HTTP_OK
-
什么是您选择的解决方案。我只有 facebook 用户图片有问题
-
解决办法是你跟着重定向
标签: java android facebook android-asynctask