正在从OpenLibrary API加载ImageView中的图像



我在AsyncTask中编写了以下程序,从互联网加载图像并在ImageView中显示。如果我提供任何直接的图像链接,该程序运行良好,但不使用API链接。

我的意思是,例如,要获得OpenLibrary中Farmer Boy的封面,我需要在html或浏览器中提供以下来源:http://covers.openlibrary.org/b/isbn/9780385533225-S.jpg

然而,如果我在浏览器中输入上面的链接,浏览器会重定向到下面的地址。http://ia700804.us.archive.org/zipview.php?zip=/12/items/olcovers4/olcovers4-M.zip&文件=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。您应该在重定向URL上打开第二个连接。若要获得重定向URL,请在连接上将setInstanceFollowRedirects设置为false,并读取标头字段中的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());

最新更新