2012-07-28 13 views
0

我似乎無法弄清楚這一點。我正在加載一個包含單個重定向的網址,而Android只在一次重定向時拋出「太多重定向」,並且它在瀏覽器中運行。這裏有一個簡單的代碼片段:Android的url.openstream給出了太多的重定向IOException

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可以很好地處理它。

感謝您的任何見解。

回答

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 
} 
+0

啊,我應該知道。在我寫的幾乎所有其他刮板類型的項目中,我都必須這樣做,我只是不認爲這次嘗試設置用戶代理。我被重定向循環拋棄了。奇怪的是,它使用命令行中的「wget」,該網站必須接受其用戶代理,但不是默認的Android代理。 – 2012-07-29 04:43:11

+0

奇怪的是,在S3 4.0.4上出現問題,但在Nexus-S 4.1.1上沒有問題。剛剛測試過。 – kinghomer 2012-10-22 13:25:55