【问题标题】:Android url.openstream gives too many redirects IOExceptionAndroid url.openstream 提供了太多重定向 IOException
【发布时间】:2012-07-27 03:31:48
【问题描述】:

我似乎无法弄清楚这一点。我正在加载一个具有单个重定向的 URL,当只有一个重定向时,Android 会抛出“重定向过多”,并且它可以在浏览器中运行。这是一个简化的代码sn-p:

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 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 可以很好地使用它。

感谢您的任何见解。

【问题讨论】:

    标签: android url ioexception


    【解决方案1】:

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

    仅仅因为它在浏览器中工作并不意味着它可以直接使用URL#openStream() - 你可能不得不欺骗服务,你实际上是一个普通的网络浏览器。

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

    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
    }
    

    【讨论】:

    • 啊,我应该知道的。在我编写的几乎所有其他刮板类型的项目中,我都必须这样做,我只是没想到这次尝试设置用户代理。我被重定向循环甩了。奇怪的是它从命令行使用“wget”,该站点必须接受它的用户代理,但不是默认的 Android 用户代理。
    • 奇怪的是,在 S3 4.0.4 上出现问题,但在 Nexus-S 4.1.1 上却没有。刚刚测试。
    猜你喜欢
    • 2021-12-16
    • 2014-03-14
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    相关资源
    最近更新 更多