views:

16

answers:

1

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" prefix 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.

A: 

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.

Pzanno