HttpClient 4.3.6 Tutorial 3rd http State Management "translation"

Source: Internet
Author: User
Tags http cookie setcookie

3rd. HTTP State Management

The initial HTTP was designed as a stateful, request/response-oriented protocol, and it was made to have no special terms in order to exchange the logical relationship request/response in a stateful session. The HTTP protocol is becoming increasingly popular and adopted, and more and more systems are using it in applications that have not previously been thought of, such as e-commerce applications. Therefore, the support of state management is very necessary.

(Netscape Communications) Netscape was the leader in Web client and server software development at the time, enabling HTTP status management on their proprietary product-based products. Later, Netscape tried to standardize the mechanism by publishing a draft specification. These efforts culminated in a formal normative definition through THERFC standard track. However, the important number of applications is still largely based on Netscape's draft, and is incompatible with official specifications. All major web browser developers feel compelled to maintain maximum compatibility with these applications, thus contributing to the formation of fragments that conform to these standards.

3.1 HTTP Cookies

An HTTP cookie is a token or status packet, and HTTP proxies and servers can maintain a session by transmitting it. Netscape engineers often refer to it as a "magic cookie".

HttpClient uses the cookie interface to represent an abstract cookie tag. In this simplest HTTP cookie structure is a pair of name/value (Name/value). Usually an HTTP cookie also contains many attributes, such as: version, valid domain name, the path to a subset of URLs specified on the source server for a cookie fete, and the maximum cookie validity period.

SetCookieThe interface behaves as a Set-cookie answer header, which is sent to the HTTP proxy by the source server in order to maintain a session state. SetCookie2interface is an extension of setcookie, it adds some special methods.

The Clientcookie interface extends the Cookie interface by adding additional customer functionality, such as being able to completely restore the original cookie attributes, as specified by the source server. This is important for generating cookie headers, because some cookie spec requests Set-Cookie Set-Cookie2 should include a certain attribute only if they are specified by the or header.

3.1.1 Cookie Version

Cookies are compatible with the draft Netscape specification, but are incompatible with the official specification of 0, but the standard compatible cookie version is 1, and httpclient may differ in the way it is processed by different versions of the cookie.

Here is an example of a refactoring Netscape cookie:

Basicclientcookie Netscapecookie = new Basicclientcookie ("name", "value"); netscapecookie.setversion (0); Netscapecookie.setdomain (". mycompany.com"); Netscapecookie.setpath ("/");

This is an example of refactoring a standard cookie. Please note that the standard compatible cookie must maintain all attributes sent from the source server.

Basicclientcookie Stdcookie = new Basicclientcookie ("name", "value"), Stdcookie.setversion (1); Stdcookie.setdomain (". MyCompany.com "); Stdcookie.setpath ("/"); Stdcookie.setsecure (true);//Set attributes exactly as sent by the server Stdcookie.setattribute (Clientcookie.version_attr, "1"); Stdcookie.setattribute (Clientcookie.domain_attr, ". MyCompany.com ");

This is an example of refactoring Set-cookie2cookie compatible cookies. Please note that the standard compatible cookie must maintain all attributes sent from the source server.

BasicClientCookie2 Stdcookie = new BasicClientCookie2 ("name", "value"), Stdcookie.setversion (1); Stdcookie.setdomain ( ". mycompany.com"); Stdcookie.setports (new int[] {80,8080}); Stdcookie.setpath ("/"); Stdcookie.setsecure (true);//Set Attributes exactly as sent by the server Stdcookie.setattribute (clientcookie.version_attr, "1"); Stdcookie.setattribute (Clientcookie.domain_attr, ". mycompany.com"); Stdcookie.setattribute (clientcookie.port_attr, "80,8080");
3.2 Cookie Specification

CookieSpecThe interface represents a cookie management specification. The cookie management specification is strictly enforced:

1, Set-cookie and arbitrary Set-Cookie2 Header analysis rules;

2. Analysis of cookie rules;

3. Format the cookie header for the specified host, port, and source path.

HttpClient contains severalCookieSpec实现:

1Netscape Draft (draft Netscape): A specification that complies with Netscape's early-release drafts. It is essential to the compatibility of traditional code;

2,Standard: RFC 2965 HTTP status Management specification;

3.Browser compatibility (browser compatible): This implementation attempts to emulate the behavior of ordinary browsers such as IE and Firefox.

4.Best match: the ' Meta ' cookie specification, which is a cookie policy based on the sending HTTP response structure as a basis. All of its implementations are concentrated in one class.

5.Ignore Cookies: (Ignore cookies): All cookies are ignored.

It is strongly recommended that you use the best match strategy to pick up an appropriate level by httpclient the execution context (execution context).

3.3 Select Cookie Policy

The cookie policy can be set and can be overloaded with HTTP requests if requested.

Requestconfig GlobalConfig = Requestconfig.custom ()        . Setcookiespec (Cookiespecs.best_match)        . Build (); Closeablehttpclient httpclient = Httpclients.custom ()        . Setdefaultrequestconfig (GlobalConfig)        . Build (); Requestconfig localconfig = requestconfig.copy (GlobalConfig)        . Setcookiespec (cookiespecs.browser_compatibility )        . Build (); HttpGet httpget = new HttpGet ("/"); Httpget.setconfig (Localconfig);

3.4 Custom Cookie Policy

In order to implement a custom cookie policy you need to implement CookieSpec 的定制 an interface, create an CookieSpecProvider implementation to create and initialize custom specifications, and finally register into httpclient. Once a custom specification is registered, it can be activated in the same manner as the standard cookie specification.

Cookiespecprovider Easyspecprovider = new Cookiespecprovider () {public Cookiespec Create (HttpContext context) {                     return new Browsercompatspec () {@Override public void validate (cookie cookie, Cookieorigin origin)    Throws Malformedcookieexception {//Oh, I am Easy}}; }}; registry<cookiespecprovider> r = registrybuilder.<cookiespecprovider>create (). Register (CookieSpecs.BE St_match, New Bestmatchspecfactory ()). Register (cookiespecs.browser_compatibility, new Browse Rcompatspecfactory ()). Register ("Easy", Easyspecprovider). Build (); Requestconfig requestconfig = Requestconfig.custom (). Setcookiespec ("Easy"). Build (); Closeablehttpclient httpclient = Httpclients.custom (). Setdefaultcookiespecregistry (R). Setdefaultrequestcon Fig (requestconfig). build ();
3.5 The persistence of cookies

HttpClient can be implemented by implementing the Cookiestore interface to support any physical expression of persistent cookie repositories. By default, the implementation of Cookiestore calls Cookiestore (a simple implementation that is supported by Java.util.ArrayList). When a container object performs a garbage collection, BasicClientCookie the cookies stored in the object are lost. If needed, users can provide more complex implementations.

Create a local instance of cookie store  translation: Creating a native Cookie Warehouse instance cookiestore Cookiestore = new Basiccookiestore ();//Populat E-Cookies if needed  : Fill in Cookiesbasicclientcookie cookie = new Basicclientcookie ("name", "value"); cookie.setversion (0); Cookie.setdomain (". mycompany.com"); Cookie.setpath ("/"); Cookiestore.addcookie (cookie);//Set the Storecloseablehttpclient httpclient = Httpclients.custom ()        . Setdefaultcookiestore (Cookiestore)        . Build ();

3.6 HTTP state management and execution context

During the execution of the HTTP request, HttpClient joins the following state-management-related objects to execute the context:

1) Lookup The instance represents the actual cookie specification registry. The value of this property takes precedence over the default in the local context file;

2)CookieSpec代表实际的cookie规格;

3) The CookieOrigin instance represents the actual detailed information about the source server;

4) CookieStore The instance represents the actual cookie warehouse. The value of this property takes precedence over the default in the local context file.

A local HttpContext object can be used to customize the HTTP state management context before the request executes, or to check the state of a request after it has finished executing. You can use the detached execution context to implement state management for each user (or each thread). The cookie specification registry and the cookie repository are defined in the local context to have a higher priority than the default set at the HTTP client level.

Closeablehttpclient httpclient = <...>Lookup<CookieSpecProvider> Cookiespecreg = <...>cookiestore Cookiestore = <...>httpclientcontext context = Httpclientcontext.create (); Context.setcookiespecregistry ( Cookiespecreg); Context.setcookiestore (Cookiestore); HttpGet httpget = new HttpGet ("http://somehost/"); Closeablehttpresponse response1 = Httpclient.execute (httpget, context); <...>//Cookie origin Detailscookieorigin Cookieorigin = Context.getcookieorigin ();//Cookie spec Usedcookiespec Cookiespec = Context.getcookiespec ();

Translator: Lianghongge

HttpClient 4.3.6 Tutorial 3rd http State Management "translation"

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.