HttpClient 4.3.6 Tutorial 3rd http State Management "translation"

Source: Internet
Author: User
Tags http cookie httpcontext setcookie

Reprint: http://blog.csdn.net/lianghongge/article/details/42027069

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:

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.

New Basicclientcookie ("name", "value"); Stdcookie.setversion (1); Stdcookie.setdomain (". MyCompany.com "); Stdcookie.setpath ("/"); Stdcookie.setsecure (true) ; //  Stdcookie.setattribute (clientcookie.version_attr, "1"". 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") Span style= "color: #000000;" ); Stdcookie.setversion ( 1". mycompany.com " Span style= "color: #000000;" ); Stdcookie.setports ( new  int  [ {80,8080 "/"  true  );  //  Set attributes exactly as sent by the server  Stdcookie.setattribute ( Clientcookie.version_attr, "1" . mycompany.com "" 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)        =  Httpclients.custom ()        . Setdefaultrequestconfig (globalconfig)        = requestconfig.copy (globalconfig)        . Setcookiespec (cookiespecs.browser_compatibility)         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 =NewCookiespecprovider () { PublicCookiespec Create (HttpContext context) {return NewBrowsercompatspec () {@Override Public voidValidate (Cookie cookie, Cookieorigin origin)throwsmalformedcookieexception {//Oh, I am Easy            }        }; }}; Registry<CookieSpecProvider> r = registrybuilder.<cookiespecprovider>Create (). Register (Cookiespecs.best_match,Newbestmatchspecfactory ()). Register (cookiespecs.browser_compatibility,Newbrowsercompatspecfactory ()). Register ("Easy", Easyspecprovider). Build (); Requestconfig Requestconfig=Requestconfig.custom (). Setcookiespec ("Easy"). build (); Closeablehttpclient httpclient=Httpclients.custom (). Setdefaultcookiespecregistry (R). Setdefaultrequestconfig (requestconfig). b Uild ();
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 the cookie store Create a local cookie warehouse instance  cookiestore cookiestore = new   Basiccookiestore ();  //  Populate Cookie if needed: Fill in the Cookies  Basicclientcookie cookie = new  Basicclientcookie ("name", "Value"  0". mycompany.com " "/"  //  Set the store  Closeablehttpclient httpclient = Httpclients.custom (). Setdefaultcookiestore (CookieS Tore). 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=NewHttpGet ("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"

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.