gpt4 book ai didi

android - 从 OpenLibrary API 在 ImageView 中加载图像

转载 作者:行者123 更新时间:2023-11-30 03:14:21 35 4
gpt4 key购买 nike

我在 AsyncTask 中编写了以下程序来从互联网加载图像并在 ImageView 中显示。如果我提供任何直接图像链接,但不使用 API 链接,程序就可以正常工作。

我的意思是,例如to have the cover of Farmer Boy from OpenLibrary ,我需要在 html 或浏览器中提供以下源代码: http://covers.openlibrary.org/b/isbn/9780385533225-S.jpg

但是,如果我在浏览器中输入上面的链接,浏览器会重定向到下面的地址。 http://ia700804.us.archive.org/zipview.php?zip=/12/items/olcovers4/olcovers4-M.zip&file=49855-M.jpg

我的问题是,我的代码适用于最后一个,但不适用于第一个。

如何使用第一个链接获取图像(在我的 android 应用程序中)?

代码:

private class getImageOpenLibrary extends AsyncTask<String, Void, Bitmap> 
{
protected Bitmap doInBackground(String... args) {
URL newurl = null;
try {
//newurl = new URL("http://covers.openlibrary.org/b/isbn/"+args[0]+"-M.jpg"); // THIS DOES NOT WORK, args[0] = 9780064400039
newurl = new URL("http://ia700804.us.archive.org/zipview.php?zip=/12/items/olcovers4/olcovers4-M.zip&file=49855-M.jpg"); //THIS WORKS
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap mIcon_val = null;
try {
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mIcon_val;
}

//@Override
protected void onPostExecute(Bitmap result1)
{
ImageView mImageView = (ImageView) findViewById(R.id.cover);
mImageView.setImageBitmap(result1);
}
}

最佳答案

您应该处理重定向。该网址重定向到另一个网址。您应该在重定向 URL 上打开第二个连接。为了能够获得重定向 URL,设置 setInstanceFollowRedirects在连接上设置为 false 并读取 header 字段中的 Location

URL url = new URL("http://covers.openlibrary.org/b/isbn/9780385533225-S.jpg");
HttpURLConnection firstConn = (HttpURLConnection) url.openConnection();
firstConn.setInstanceFollowRedirects(false);
URL redirectURL = new URL(firstConn.getHeaderField("Location"));
URLConnection redirectConn = redirectURL.openConnection();
Bitmap bitmap = BitmapFactory.decodeStream(redirectConn.getInputStream());

关于android - 从 OpenLibrary API 在 ImageView 中加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20399547/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com