J_Hopper
J_Hopper

Reputation: 77

Android url.openstream gives too many redirects IOException

I can't seem to figure this out. I'm loading a URL that has a single redirect, and Android is throwing "Too many redirects" when there is only a single redirect, and it works in a browser. Here's a simplified code snippet:

URL url = null;
InputStream in;
String pic_url = "http://www.cdn.sherdog.com/image_crop/200/300/_images/fighter/20100221121302_bader.JPG";
try { url = new URL(pic_url); }
catch (MalformedURLException e1) { Log.d("iTrackMMA","URL had exception malformedURLEx on: " + pic_url); }

try { in = url.openStream(); }
catch (IOException ioe) { Log.d("iTrackMMA","URL had IOException on: " + pic_url + " with error: " + ioe.getMessage()); }

Error:

07-28 21:57:38.017: URL had IOException on: http://www.cdn.sherdog.com/image_crop/200/300/_images/fighter/20100221121302_bader.JPG with error: Too many redirects

If I use the URL that this redirects to, to cut out any redirects, I still get the same error, even though there doesn't seem to be any redirect?

URL url = null;
InputStream in;
String pic_url = "http://m.sherdog.com/image_crop.php?image=http://www.cdn.sherdog.com/_images/fighter/20100221121302_bader.JPG&&width=200&&height=300";
try { url = new URL(pic_url); }
catch (MalformedURLException e1) { Log.d("iTrackMMA","URL had exception malformedURLEx on: " + pic_url); }

try { in = url.openStream(); }
catch (IOException ioe) { Log.d("iTrackMMA","URL had IOException on: " + pic_url + " with error: " + ioe.getMessage()); }

Error:

07-28 21:48:31.337: URL had IOException on: http://m.sherdog.com/image_crop.php?image=http://www.cdn.sherdog.com/_images/fighter/20100221121302_bader.JPG&&width=200&&height=300 with error: Too many redirects

What am I missing? Does it do this for others as well? I'm wondering if there's something non-HTML compliant about this URL, and if so, I hope to find a workaround so that Android will play nice with it.

Thanks for any insight.

Upvotes: 1

Views: 1827

Answers (1)

Jens
Jens

Reputation: 17077

Since the server is dishing up a redirect it obviously has some sort of request filtering running - which may be of questionable quality (more likely than not).

Just because it works in a browser doesn't mean it will work with a straight URL#openStream() - you may have to trick the service that you are in fact a normal web browser.

In your case, try doing the following:

try {
    URL url = new URL(pic_url);
    URLConnection conn = url.openConnection();
    // Spoof the User-Agent of a known web browser
    conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
    in = conn.getInputStream();
} catch (MalformedURLException e) {
    // Error handling goes here
} catch (IOException e) {
    // Error handling goes here
}

Upvotes: 4

Related Questions