HttpURLConnection in the JDK has a bizarre bug. When it receives a HTTP response code in the 3xx range, it performs redirection to the web page mentioned in the “Location” header. However, when it does this, it forgets to send all the cookies with the request. Therefore, if you are working with any of the web 2.0 APIs which perform redirection and require this authentication cookie with each request, you are doomed because the server will redirect to the login page thinking that this is an unauthenticated request.

The solution for this is pretty simple. If you have written code like below:

URL u = new URL(“http://www.example.com”);

HttpURLConnection conn = (HttpURLConnection) u.openConnection();

You have to add one more line that sets redirection to “FALSE” & do the redirection yourself with the cookies, which becomes like:

URL u = new URL(“http://www.example.com”);

HttpURLConnection conn = (HttpURLConnection) u.openConnection();

conn.setInstanceFollowRedirects(false); // do not redirect

String locHeader = conn.getHeaderField(“Location”); // get the location

String cookies = conn.getHeaderField(“Set-Cookie”); // get the cookie

u = null; conn = null;

u = new URL(locHeader);

conn = (HttpURLConnection) u.openConnection();

conn.setRequestProperty(“Cookie”, cookies); // set the cookie yourself

….

Done! That should solve the bug. If this seems too much to do, then you should consider using this excellent HttpClient library from Apache.

I did the above mentioned stuff for this Free SMS Java Library because:

  1. The library has to be very small because it is just one file.
  2. Eliminate external dependencies that will bloat the library.
There you go! Now, if you have encountered this bug you have the solution to squash it. Have fun!

Hey guys, after quite a long time, assume about 3 years, I have cleaned my small room over this weekend… much to the surprise of my mom ofcourse ;-). It took about 5 hours of day one and another 3 hours of day two to complete it in all glory. Next on line is my blog, which wasn’t touched except for doing new posts. Have to get a nice new template soon. Any suggestions?

————————————————-

Java SE 6 is out. The whole Java community is gaga over it. Netbeans 5.5 now supports Java SE 6 also. Reading this yesterday, I feel Sun is committed to not making that mistake. The next Sun Tech Days event is happening at Hyderabad on 21-23 Feb 2007. The talks look promising and the topics they pick everytime are exciting. They have also added a Java ME day this time. If you are a java freek, DON’T miss this event. Register.

————————————————-

Proto has been going on great. The website now sports a new dress skin. If you are a startup company willing to showcase your product at Proto, nominate yourself. The nomination closes on 20th Dec 2006. Registration for other participants will be open soon. So, hang on! Read the Proto blog for more information.

Wow!! exciting times ahead.