I'm trying to write a program to do automated testing on my webapp. To accomplish this, I open up a connection using HttpURLConnection.
One of the pages that I'm trying to test performs a 302 redirect. My test code looks like this :
URL currentUrl = new URL(urlToSend);
HttpURLConnection connection = (HttpURLConnection) currentUrl.openConnection();
connection.connect();
system.out.println(connection.getURL().toString());
So, let's say that urlToSend is http://www.foo.com/bar.jsp, and that this page redirects you to http://www.foo.com/quux.jsp. My println statement should print out http://www.foo.com/quux.jsp, right?
WRONG.
The redirect never happens, and it prints out the original URL. However, if I change switch out the connection.connect() line with a call to connection.getResponseCode(), it magically works.
URL currentUrl = new URL(urlToSend);
HttpURLConnection connection = (HttpURLConnection) currentUrl.openConnection();
//connection.connect();
connection.getResponseCode();
system.out.println(connection.getURL().toString());
Why am I seeing this behavior? Am I doing anything wrong?
Thanks for the help.
URLConnection is the base class. HttpURLConnection is a derived class which you can use when you need the extra API and you are dealing with HTTP or HTTPS only. HttpsURLConnection is a 'more derived' class which you can use when you need the 'more extra' API and you are dealing with HTTPS only.
Calling URL#openConnection() on a URL with the "https" scheme will return an HttpsURLConnection , which allows for overriding the default HostnameVerifier and SSLSocketFactory .
The getResponseMessage is a method of Java HttpURLConnection class. This method is used to get response code from HTTP response message. For example, if the response code from a server is HTTP/1.0 200 OK or HTTP/1.0 404 Not Found, it extracts the string OK and Not Found else returns null if HTTP is not valid.
The connect()
method just creates a connection. You have to commit the request (by calling getInputStream()
, getResponseCode()
, or getResponseMessage()
) for the response to be returned and processed.
The connect() method is implemented in the URLConnection class, and is not overridden by the HttpURLConnection class.
The URLConnection class is not aware of HTTP, and so should not follow the HTTP redirect even if it was creating a real connection.
If you want behaviour intrinsic to the HTTP protocol, you probably want to stick to methods implemented in the HttpURLConnection class, as the getResponseCode() method is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With