jump to navigation

Java HttpURLConnection with redirect March 16, 2007

Posted by javafoo in java, java http.
trackback

So I am trying to automate an application A at work, that needs to talk to another system B(also j2ee based), via http. But system B does not expose its applications as services and also certain applications need a user to login. So here’s what I do, I decide to write a http client that will emulate a login on system B (it’s a jsp on system B), grab the session cookie and then call the protected servlet on System B. Sounds simple enough.

But looks like it was going to be a long evening. I call login.jsp on system B and look at the logs on system B, seems like system B liked the username and password and it was also passing back the session cookie to my http client. But the subsequent call to the servlet in system B was failing, due to invalid authentication. After spending a couple of hours trying to debug my http client, I realize that the login.jsp on System B is doing a http redirect (well the HTTP 302 code should have tipped me off), so even though I was using the correct username and password the authentication was failing. So I add setInstanceFollowRedirects(false) on the HttpURLConnection object and everything starts working.  I don’t really care about the content that login.jsp delivers, so my client does not need to redirect. There is also a setFollowRedirects(boolean) static method that works on the class, so use caution when using this method as opposed to the instance method.

That is my lesson for the day and I will stick my head out of the window for a blast of that chilly mid western breeze.

Comments»

1. lando - September 25, 2008

Is it possible to see a java code example?

2. Mody - October 25, 2008

Thanks for sharing this tip
but can I ask what setInstanceFollowRedirects(false) does?
why did it work when you used that method

The Amazing JAVA