Domanda

Given a URL string, I want to get an HTTP-connection to the "final" (non-redirected) URL:

  • If the response-code is 2xx, then I can simply use the initial connection.

  • If the response-code is 3xx, then I need to open a new connection and try again.

  • For any other response-code (such as 4xx or 5xx), I "give up" and return null.

My code is given below:

HttpURLConnection getConnection(String url) throws Exception
{
    HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
    while (true)
    {
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("User-Agent","");
        int responseCode = connection.getResponseCode();
        switch (responseCode/100)
        {
        case 2:
            return connection;
        case 3:
            switch (responseCode)
            {
            case 300:
                connection = ???
                break;
            case 301:
            case 302:
            case 303:
            case 305:
            case 307:
                connection = (HttpURLConnection)new URL(connection.getHeaderField("Location")).openConnection();
                break;
            case 304:
                connection = ???
                break;
            default:
                return null;
            }
            break;
        default:
            return null;
        }
    }
}

My questions are hereby:

  1. How should I handle response-codes 300 and 304?

  2. Am I handling response-codes 301, 302, 303, 305 and 307 correctly?

Any other constructive comments on the method above will also be appreciated.

Thanks

È stato utile?

Soluzione

Although all of these are some kind of redirects, it's tricky to come up with a model to handle them all.

You may want to read http://greenbytes.de/tech/webdav/draft-ietf-httpbis-p2-semantics-26.html#rfc.section.6.4 for more information.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top