Android url.openstream给出了太多重定向IOException

时间:2012-07-28 22:02:16

标签: android url ioexception

我似乎无法弄清楚这一点。我正在加载一个只有一个重定向的网址,当只有一个重定向时Android会抛出“太多的重定向”,并且它在浏览器中有效。这是一个简化的代码片段:

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()); }

错误:

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

如果我使用重定向到的网址,为了删除任何重定向,我仍会得到相同的错误,即使似乎没有任何重定向?

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()); }

错误:

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

我错过了什么?它也会为其他人这样做吗?我想知道是否有关于此URL的非HTML兼容性,如果是这样,我希望找到一种解决方法,以便Android能够很好地使用它。

感谢您的任何见解。

1 个答案:

答案 0 :(得分:4)

由于服务器正在进行重定向,因此它显然会运行某种请求过滤 - 这可能质量有问题(更有可能)。

仅仅因为它在浏览器中有效并不意味着它可以使用直接URL#openStream() - 您可能必须欺骗该服务,您实际上是一个普通的Web浏览器。

在您的情况下,请尝试执行以下操作:

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
}