IntroductionHttpClient supports automatic management of cookies, including allowing the server to set cookies and automatically return them to the server when required. It is also possible to manually set cookies to be sent to the server. Unfortunately, there are two major standards for handling Cookies, RFC2109 and the Netscape Cookie draft, and a large number of implementations are completely non-standard. To deal with this, HttpClient provides configurable cookie specifications. This guide will explain how to use the different cookie specifications and identify some of the common problems people have when using Cookies and HttpClient. Available SpecificationsThe following cookie specifications are supported by HttpClient. RFC2109RFC2109 is the final published specification released by the W3C. Theoretically, all servers that handle cookies should use this specification and as such this specification is used by default within HttpClient. Unfortunately, many servers either incorrectly implement this standard or are still using the Netscape draft so occasionally this specification is too strict. If this is the case, you should switch to the compatibility specification as described below. RFC2109 is available at http://www.w3.org/Protocols/rfc2109/rfc2109.txt Netscape DraftThe Netscape draft is the original cookie specification which formed the basis for RFC2109. Despite this it has some significant differences with RFC2109 and thus may be required for compatibility with some servers. The Netscape cookie draft is available at http://wp.netscape.com/newsref/std/cookie_spec.html CompatibilityThe compatibility specification is designed to be compatible with as many different servers as possible even if they are not completely standards compliant. If you are encountering problems with parsing cookies, you should probably try using this specification. Specifying the SpecificationThere is two ways to specify which cookie specification should be used, either for each HttpState instance, or by setting the default for newly created HttpState instances. Per HttpState
In most cases, the best way to set which cookie specification to use
is using the
HttpClient client = new HttpClient(); client.getState().setCookiePolicy(CookiePolicy.COMPATIBILITY); Default
The default cookie specification can be set by setting the system
property
This setting will be used by any newly created HttpState objects, however existing HttpState instances will not be affected. System.setProperty("apache.commons.httpclient.cookiespec", String.valueOf(CookiePolicy.COMPATIBILITY)); Common ProblemsThe most common problems encountered with parsing cookies is due to non-compliant servers. In these cases, switching to the compatibility cookie specification usually solves the problem. |