2010-08-26 47 views
2

我試圖從一個網站解析一個xml文件。比方說,該網站是「http://example.com改寫後的Android InputStream

這個網站有一個htaccess的重寫規則設置重定向與一個「www」的前綴到主機回example.com什麼。所以「http://www.example.com」將重定向到「http://example.com

在我的代碼中我有一個URL,我得到的InputStream的。

protected InputStream getInputStream() { 
    try { 
     return feedUrl.openConnection().getInputStream(); 
    } catch (IOException e) { 
     throw new RuntimeException(e); 
    } 
} 

在這種情況下feedUrl被poingting爲「http://www.example.com/file.xml」當我做到以下幾點:

try { 
    Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, root.getContentHandler()); 
} catch (Exception e) { 
    throw new RuntimeException(e); 
} 

我得到一個異常拋出,我相信它不是重定向到「http://example.com/file.xml

我顯然可以靜態地改變我的feedUrl變量指向的位置,但我需要這是動態的。

回答

3

如果有人遇到了像我這樣的問題,那麼這裏就是解決方案。如果響應代碼是300,301,302或303,則HttpURLConnection已經設置爲遵循重定向。

由於某些原因,我解析的服務器需要響應代碼爲307不自動重定向。

我會建議使用不同的響應代碼,但如果您的服務器需要它,那麼這裏的解決方法。

HttpURLConnection conn = (HttpURLConnection) feedUrl.openConnection(); 
int responseCode = conn.getResponseCode(); 
if(responseCode == 307){ 
    String location = conn.getHeaderField("location"); 
    feedUrl = new URL(location); 
    conn = (HttpURLConnection) this.feedUrl.openConnection(); 
} 

現在conn可以打開輸入流到正確的文件。