Invoking URL that sets cookie through JSP/Servlets

I have an external URL that I have to invoke that will set a cookie, and I have verified in a browser that it does set the cookie correctly. But, I need to call the URL programmatically through JSP/Servlets. I tried using URLConnection (<url>.openConnection(), then connect()), and it does not set cookies the URL would set if called by a browser.

How do I do this?

Thanks.

[398 byte] By [bliplea] at [2007-10-2 6:17:57]
# 1

You might need to inspect the HTTP headers of the request that your browser sends versus what you sent. One way to easily see this is to hook up a proxy to your browser and have your Servlet also send its requests there. If the HTTP headers differ, that might be the culprit.

One other note: you can download the Jakarta Commons HttpClient. You generally work with that API more easily than the URLConnection. Though that is just personal preference on my part.

- Saish

Saisha at 2007-7-16 13:19:53 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2
Does this mean that URLConnection alone should set the browser cookie, i.e., no additional work should be needed?Thanks.
bliplea at 2007-7-16 13:19:53 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 3

No. You would use HttpUrlConnection. When you get the response from the other server back, you need to look for 'set-cookie' headers in the response. You can inspect the headers via getHeaderFieldKey(int) and then getHeaderField(int). Once you get the cookie you need to set, you will use your HttpServletResponse object and call addCookie(), passing the same information back to the client browser.

- Saish

Saisha at 2007-7-16 13:19:53 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 4

Thanks for the help.

I had tried that previously, but the cookie only gets set when I ignore the cookie domain (I am assuming this is a security measure to not allow cookie spoofing).

The domain must be set in the cookie I am trying to set, otherwise the auto-login on the external site will not work.

Is there a way around this, or an alternative way to set the cookie?

Thanks.

bliplea at 2007-7-16 13:19:53 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 5

You can, in effect, proxy the cookie setting if you like. Have the cookie apply to your domain. The browser should honor the set-cookie request like any other web site (depending on the user's preferences). You then would then re-forward the cookie to the server requiring authentication when the user submits requests to your server. Do a quick Google on how web proxies work. Squid is a popular linux/unix proxy.

- Saish

Saisha at 2007-7-16 13:19:53 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...