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.
Is it possible to see a java code example?
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
Jeje,
I found this post AFTER spending that bunch of hours, trying to find out why my request returned 200 OK, instead of 302 Moved.
I needed to send some cookies to the after-login request, but, as it did some under-the-hood magic and followed the redirect (without sendind those cookies, of course), it returned the “not-logged-in” page and that’s a 200 OK response.
You can see a full example here:
http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests (in the case you or anyone need it two and a half year after the original post, though)
[...] thought I knew this at some point when I was doing this. But today, it had me searching [...]