views:

209

answers:

2

I am trying to login and retrieve status information from a HTTPS URL via Java programming. I login through /login.cgi, providing the username and password with a POST request to that script.

The script then verifies the credentials and creates a specific cookie (with session information, user name, etc.) and then immediately calls a Location response header to /home.cgi. Which, I'm guessing, the /home.cgi script verifies the cookie information before continuing to load. Otherwise, it just reverts back to the /login.cgi page.

All of this works fine within a browser because of the way browser's handle cookies/sessions correctly. However, within Java, this is very tricky because I can not get the appropriate cookie to send as a request to subsequent pages. I can not get the correct cookie because I am unable to get the HTTP response back (which holds the correct "Set-cookie" value) in between /login.cgi creating the specific cookie and it calling Location /home.cgi.

Is there something I'm missing or is there a better way that Java can handle cookies similar to a browser? (is there a cookie store, etc?)

Thanks for the help,

Steve

+1  A: 

How are you making the HTTP connections and managing cookies?

I would recommend just using commons-httpclient rather than managing this yourself. It will automatically manage cookies for you.

matt b
Which advantage do you expect from Commons HTTPClient compared to the built-in standard API?
jarnbjo
It's API was a whole lot easier to use than the standard one, although I'm not familiar with any recent updates to java.net stuff.
matt b
+3  A: 

Cookie management is by default not enabled in the java.net HTTP API. If you don't need any specific handling or cross-application cookie persistence (the cookies will be deleted when your application terminates), you can simple enable it with

CookieHandler.setDefault(new CookieManager());
jarnbjo
So this statement will automatically enable cookies within the Java program similar to that of a browser?
stjowa
Yes, you can simply invoke it at the start of your main method, and later all HTTP requests through java.net.URL will use a cookie store similar to how browsers handle cookies.
jarnbjo
Yes, this worked. However, I had to adjust the cookie policy on it to accept all cookies.CookieManager customCookieManager = new CookieManager();customCookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);CookieHandler.setDefault(customCookieManager);Thanks for the help.
stjowa