Java HttpURLConnection with redirect March 16, 2007Posted by javafoo in java, java http.
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.