Java URLConnection.getURL() only redirects after seemingly unconnected methods are called

117 views Asked by At

The following piece of code should print out the new location of a website that uses the Location header to redirect to a new page/file (http://somepagethatredirects.me/after.txt):

URL website = new URL("http://somepagethatredirects.me/before.txt");
URLConnection urlConnection = website.openConnection();
System.out.println(urlConnection.getURL());

Even though we expect the location to be http://somepagethatredirects.me/after.txt, we get the URL parameter specified.

Adding a (seemingly unconnected) method like urlConnection.getHeaderField("Location"), urlConnection.getHeaderFields() or even urlConnection.getExpiration() will (strangely) give us the expected result:

URL website = new URL("http://somepagethatredirects.me/before.txt");
URLConnection urlConnection = website.openConnection();
urlConnection.getHeaderFields();
System.out.println(urlConnection.getURL());

Is this intended behaviour? It seems like a bug to me.


Edit 1: As Jeffrey Bosbom pointed out, calling urlConnection.openConnection() doesn't actually establish a connection to the server, urlConnection.connect() does (or other methods that imply an active connection). This doesn't change the program's output however:

URL website = new URL("http://somepagethatredirects.me/before.txt");
URLConnection urlConnection = website.openConnection();
urlConnection.connect();
System.out.println(urlConnection.getURL());
1

There are 1 answers

0
user207421 On

Nothing happens in terms of HTTP transactions until you either:

  • get the response code
  • open the input stream
  • open the error stream.

I'm not sure that even after that you have any basis for expecting getURL() to deliver the final target URL.