从OpenLibrary API在ImageView中加载图像

问题描述 投票:1回答:1

我在AsyncTask中编写了以下程序,从Internet加载图像并在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);
        }
    }
android bitmap imageview uri bitmapfactory
1个回答
1
投票

您应该处理重定向。该网址会重定向到另一个网址。您应该在重定向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());
© www.soinside.com 2019 - 2024. All rights reserved.