0

My company doesn't use Apache, so we've spun up our own socket code. In the following, HTMLDoc is my version of a server response. I'm trying to grab the URL that a browser would redirect to if the original URL gave a 301 response code:

    static public void main(String args[]) throws Exception
{

    String spec = "http://some_url_with_301_redirect.com";
    URL my_url = new URL(spec);

    HTMLDoc doc = getDocFromURL(my_url);

    // Do stuff with the doc.
}

public static HTMLDoc getDocFromURL(URL url)
{
    try
    {
        URLConnection u = url.openConnection();

        if ( u instanceof HttpURLConnection )
        {
            HttpURLConnection http_u = (HttpURLConnection)u;

            int response_code = http_u.getResponseCode();

            if (response_code == 300 || response_code == 301 || response_code == 302)
            {
                URL redirected_url = getRedirectedURL(url);

                return getDocFromURL(redirected_url);
            }
        }

        return null;
    }

    catch(Exception e) 
    {
        e.printStackTrace();
        return null;
    }
}

The trouble is, I have no idea what the method getRedirectedURL(url) should look like. Is there a quick call I can do to http_u that I'm not familiar with?

Sal
  • 3,179
  • 7
  • 31
  • 41

1 Answers1

1

A HTTP 301 response is always accompanied by a Location header. A typical response looks looks like

HTTP/1.1 301 Moved Permanently
Location: http://www.example.org/index.asp

You can read this header and get the redirected URL. The sample code to do this is mentioned in the link posted by Jon Lin in the comments above.

Community
  • 1
  • 1
Santosh
  • 17,667
  • 4
  • 54
  • 79