Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Add the following in your onCreate

StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 

Why don't you use HttpClient from apache.

Try setFollowRedirects, as it might help. Actually, try getFollowRedirects to see if it's the problem, first (unlikely since it's true by default).

Edit: If this is not your problem, I would try reading something from the connection (as you do with getResponseCode but I would try also getHeaderField to see if reading anything at all causes the redirect to be respected).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top