Question

I have written the below program in AsyncTask to load image from internet and show in ImageView. The program works fine if I give any direct image link, but don't work with API links.

What I mean is, for example, to have the cover of Farmer Boy from OpenLibrary, I need to give below source in html or in browser: http://covers.openlibrary.org/b/isbn/9780385533225-S.jpg

However, if I enter above link in browser, the browser redirect to below address. http://ia700804.us.archive.org/zipview.php?zip=/12/items/olcovers4/olcovers4-M.zip&file=49855-M.jpg

My problem is, my code works with last one, but not with the first one.

How can I get the image (in my android application) using the first link?

CODE:

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);
        }
    }
Was it helpful?

Solution

You should handle the redirection. The url redirects to another URL. You should open a second connection on the redirect URL. To be able to get the redirect URL, set setInstanceFollowRedirects to false on the connection and read the Location in the header fields.

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());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top