Thursday, November 1, 2012

Determining redirects when accessing an URL

Here’s a basic example on how to determine when opening a HTTP request, if the URL redirects to another one. The function of this class gets the HTTP response code from the HTTP connection, and if the code is any of the ones associated with redirection: 301/302/303, it obtains the final destination from the "Location" header.

import java.net.HttpURLConnection;
import java.net.URL;

public class URLUtils {
    /**
     * Prints the redirect URL for the provided input URL (if it applies). 
     * @param url
     */
    public static void printRedirect(String url) {
        try {
            URL urlToPing = new URL(url);
            HttpURLConnection urlConn = (HttpURLConnection) urlToPing.openConnection();
            // Needed to check if it is a redirect. 
            urlConn.setInstanceFollowRedirects(false);
            // It's any of these response codes: 301/302/303 
            if (urlConn.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM 
               || urlConn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP 
               || urlConn.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER) {
                System.out.println("URL <" + url + "> redirects to: <" + urlConn.getHeaderField("Location") + ">, Response Code: " + +urlConn.getResponseCode());
            } else {
                System.out.println("URL <" + url + "> has no redirect, Response Code: " + urlConn.getResponseCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        URLUtils.printRedirect("http://www.google.com");
        URLUtils.printRedirect("http://www.crjug.org");
    }
} 

Result:
URL <http://www.google.com> redirects to: <http://www.google.co.cr/>, Response Code: 302
URL <http://www.crjug.org> has no redirect, Response Code: 200

No comments:

Post a Comment