开发者

Android InputStream following a rewriterule

开发者 https://www.devze.com 2023-01-13 13:04 出处:网络
I\'m trying to parse an xml file from a website. Let\'s say the website is \"http://example.com\" This website has a htaccess rewrite rule setup to redirect anything with a \"www\" prefi开发者_StackO

I'm trying to parse an xml file from a website. Let's say the website is "http://example.com"

This website has a htaccess rewrite rule setup to redirect anything with a "www" prefi开发者_StackOverflow社区x to the host back to example.com. so "http://www.example.com" would redirect to "http://example.com"

In my code I have a URL that i get the InputStream of.

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

In this case feedUrl is poingting to "http://www.example.com/file.xml" and when I do the following:

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

I get an exception thrown and I believe it's not redirecting to "http://example.com/file.xml"

I could obviously just statically change where my feedUrl variable is pointing to, but I need this to be dynamic.


If anyone ran into this problem like I did, then here's the solution. The HttpURLConnection is already setup to follow redirects by default if the response code is 300, 301, 302, or 303.

For some reason, the server I'm parsing from needs to have the response code be 307 which Android does not redirect automatically.

I would suggest using a different response code, but if your server needs it then here's work around.

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

Now conn can open an input stream to the correct file.

0

精彩评论

暂无评论...
验证码 换一张
取 消