Android FileNotFound Exception - Cannot getInputStream from image URL that does not have file format
Asked Answered
P

2

3

The title is pretty self explanatory.

the following code...:

    URL imageUrl = new URL(url);
   try {
                HttpURLConnection conn= (HttpURLConnection)imageUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();
                return BitmapFactory.decodeStream(is);
           } catch (IOException e) {
            e.printStackTrace();
           }

Will fail if the url does not contain the file format. For example, some images hosted by google will display the image yet not have the file format (.png, .jpg, etc) as part of the url.

As a result, the content-type header of the url connection returns "text/html". I believe this is the issue.

I have tried setting a new content-type header, but that doesnt seem to change anything.

anybody know a workaround?

thanks.

Puritanical answered 18/11, 2010 at 19:39 Comment(1)
Can you give an example URL that fails?Cuspidation
S
7

I was running into problems and I remembered googling around and this was my final solution

        try {
            URL url = new URL(imageUrl);
            HttpGet httpRequest = null;

            httpRequest = new HttpGet(url.toURI());

            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);

            HttpEntity entity = response.getEntity();
            BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
            InputStream input = bufHttpEntity.getContent();

            Bitmap bitmap = BitmapFactory.decodeStream(input);

            ImageActivity.this.i.setImageBitmap(bitmap);
            ImageActivity.this.i.refreshDrawableState();
            input.close();

        } catch (MalformedURLException e) {
            Log.e("ImageActivity", "bad url", e);
        } catch (Exception e) {
            Log.e("ImageActivity", "io error", e);
        }
Splasher answered 18/11, 2010 at 21:47 Comment(1)
this was the fix! thanks Aaron! I imagine the fix worked because of utilizing Apache's HttpGet, HttpClient, HttpResponse, and HttpEntity objects. These superseded the HttpUrlConnection object, and obviously handle some things better. Im not super familiar with the BufferedHttpEntity, but that probably has a big thing to do with it too.Puritanical
K
0

BitmapFactory.decodeStream only reads the raw byte stream of the image itself, it has no knowledge about the URL nor the Content Encoding, so I don't think they are at fault here. It should be able to read the image format directly from the image header.

Probably the URL gets redirected.

Kliment answered 18/11, 2010 at 21:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.