Httpclient HTTP Status Management

Source: Internet
Author: User
Tags http cookie rfc

HTTP Status Management

The original HTTP is designed as a stateless request/response-oriented protocol. It does not have special provisions and is stateful and runs through some logically related request/response exchange sessions. As HTTP protocol is becoming increasingly popular and popular, more and more systems that have never intended to use it have begun to use it for applications, such as transmission methods for e-commerce applications. Therefore, it is necessary to support status management.

Netscape was once the leader for web clients and server software developers, and implemented support for HTTP status management in their proprietary products. Afterwards, Netscape tried to regulate this mechanism by publishing a draft Specification. Their efforts have facilitated these normative definitions through RFC standard tracking. However, status management in many applications is still based on Netscape's draft and is not compatible with official specifications. Many major Web browser developers feel it is necessary to retain those applications that greatly promote the compatibility of standard snippets.

3.1 HTTP cookies

Cookie is a token or short packet that the HTTP proxy and the target server can exchange to maintain session status information. Wangjing engineers use it to refer to the "magic cookies" and sticking names.

Httpclient uses the cookie interface to represent the abstract cookie token. In its simple form, the HTTP cookie is almost a name/value pair. Generally, an HTTP cookie contains some attributes, such as the version number, valid domain name, and specifies the path of the URL subset of the source server where the cookie application is located. The maximum cookie validity period is exceeded.

The setcookie interface indicates the header information set-cookie in the response sent by the source server to the HTTP proxy to maintain a dialog state. The setcookie2 interface extends the setcookie with the specified Set-Cookie2 method.

The setcookie interface and additional capabilities such as the ability to obtain the original cookie attributes, like the cookie interface they are extended by the client-specific functions specified by the source server. This is important for generating the cookie header, because some cookie specifications are required. The cookie header should contain specific properties specified in the Set-cookie or Set-Cookie2 header.

3.1.1 cookie version

Cookie is compatible with Netscape's draft standards, but version 0 is considered not to comply with official specifications. The expected cookie version is 1. Httpclient can process cookies of different versions.

Here is an example of re-creating a draft cookie for Netscape:

Basicclientcookie netscapecookie = new basicclientcookie ("name", "value ");

Netscapecookie. setversion (0 );

Netscapecookie. setdomain (".mycompany.com ");

Netscapecookie. setpath ("/");

This is an example of recreating a standard cookie. Note that all the attributes sent by the source server must be retained for standard cookies:

Basicclientcookie stdcookie = new basicclientcookie ("name", "value ");

Stdcookie. setversion (1 );

Stdcookie. setdomain (".mycompany.com ");

Stdcookie. setpath ("/");

Stdcookie. setsecure (true );

// Precisely set the attributes sent by the server

Stdcookie. setattribute (clientcookie. version_attr, "1 ");

Stdcookie. setattribute (clientcookie. domain_attr, ".mycompany.com ");

This is an instance that re-creates a Set-Cookie2 compatible cookie. Note that all the attributes sent by the source server must be retained for standard cookies:

Basicclientcookie2 stdcookie = new basicclientcookie2 ("name", "value ");

Stdcookie. setversion (1 );

Stdcookie. setdomain (".mycompany.com ");

Stdcookie. setports (New int [] {80, 8080 });

Stdcookie. setpath ("/");

Stdcookie. setsecure (true );

// Precisely set the attributes sent by the server

Stdcookie. setattribute (clientcookie. version_attr, "1 ");

Stdcookie. setattribute (clientcookie. domain_attr, ".mycompany.com ");

Stdcookie. setattribute (clientcookie. port_attr, "80, 80 ");

3.2 cookie Specification

The cookiespec interface represents the cookie Management Specification. The cookie management specifications are as follows:

  • The resolved set-Cookie rule also has optional Set-Cookie2 header information.

  • Verify the cookie parsing rules.

  • Format the cookie header, original port, and path of the specified host.

Httpclient comes with the implementation of cookiespec:

  • Wangjing company draft: This specification complies with the original draft Specification released by Wangjing communication. Avoid this unless it is absolutely necessary to be compatible with legacy code.

  • RFC 2109: the old version that has been replaced by the official HTTP Status Management Specification and is replaced by RFC 2965.

  • RFC 2965: Official HTTP status management specifications.

  • Browser compatibility: This implementation strives to closely imitate the implementation of (MIS) General Web browser applications. For example, Microsoft's Internet Explorer and Mozilla's Firefox browser.

  • Best Match: The 'meta' cookie specification uses some cookie policies based on the cookie format sent in HTTP response. It basically aggregates all the above implementations into a class.

We strongly recommend that you use the best match policy to enable httpclient to adopt appropriate compatibility levels based on the execution context at runtime.

3.3 HTTP cookie and status management parameters

These are parameters used to customize HTTP status management and independent cookie standard behavior.

  • 'Http. Protocol. Cookie-datepatterns ': defines the valid date format used to parse non-standard expires attributes. However, if the compatibility does not comply with the requirements, the expires defined by the Netscape draft will still be used instead of the standard max-age attribute server. This parameter is expected to get a value of the Java. util. collection type. The collection element must be of the Java. Lang. string type to be compatible with the java. Text. simpledateformat syntax. If this parameter is not set, the default value is cookiespec. Pay attention to the application of this parameter.

  • 'Http. Protocol. Single-cookie-header': defines whether the cookie should be forced to an independent cookie request header. Otherwise, each cookie is formatted as a separate cookie header. This parameter is expected to get a value of the Java. Lang. boolean type. If this parameter is not set, the default value is cookiespec. Note that this parameter is only applicable to Cookie specifications (RFC 2109 and RFC 2965 ). Browser compatibility and Netscape's draft policy will place all cookies in a request header.

  • 'Http. Protocol. Cookie-Policy': defines the name of the cookie specification used for HTTP status management. This parameter is expected to get a value of the Java. Lang. string type. If this parameter is not set, the valid date format is the standardized value of cookiespec.

3.4 cookie specification Registry

Httpclient uses the cookiespecregistry class to maintain an available cookie standard registry. The following specifications are registered for each default:

  • Compatibility: browser compatibility (loose policy ).

  • Netscape: Draft of Netscape.

  • Rfc2109: RFC 2109 (an out-of-date strict policy ).

  • Rfc2965: RFC 2965 (compliant with strict policy standards ).

  • Best-Match: the best match meta policy.

3.5 select a cookie Policy

The cookie policy can be set on the HTTP client. If necessary, it can be rewritten at the HTTP Request level.

Httpclient = new defaulthttpclient ();

// Enforce a strict cookie policy for each default

Httpclient. getparams (). setparameter (

Clientpnames. cookie_policy, cookiepolicy. rfc_2965 );

Httpget = new httpget ("http://www.broken-server.com /");

// Overwrite the Default policy for this request

Httpget. getparams (). setparameter (

Clientpnames. cookie_policy, cookiepolicy. browser_compatibility );

3.6 customize cookie policies

To implement custom cookie policies, we should create a custom implementation class for the cookiespec interface, create a cookiespecfactory implementation to create and initialize a custom implementation instance, and register the factory with httpclient. Once the custom implementation is registered, it can have the same activity as the standard cookie implementation.

Cookiespecfactory CSF = new cookiespecfactory (){

Public cookiespec newinstance (httpparams Params ){

Return new browsercompatspec (){

@ Override

Public void validate (cookie, cookieorigin origin)

Throws malformedcookieexception {

// This is quite simple

}

};

}

};

Defaulthttpclient httpclient = new defaulthttpclient ();

Httpclient. getcookiespecs (). Register ("easy", CSF );

Httpclient. getparams (). setparameter (

Clientpnames. cookie_policy, "easy ");

3.7 cookie persistence

Httpclient can be used together with persistent cookie storage that implements the cookiestore interface in any physical representation. The default cookiestore implementation is called basicclientcookie, which is a simple implementation of Java. util. arraylist. Cookies stored in the basicclientcookie object are lost when the container object is recycled by the garbage collection mechanism. If necessary, users can provide more complex implementations.

Defaulthttpclient httpclient = new defaulthttpclient ();

// Create a local cookie store instance

Cookiestore = new mycookiestore ();

// Fill in the cookie if needed

Basicclientcookie = new basicclientcookie ("name", "value ");

Cookie. setversion (0 );

Cookie. setdomain (".mycompany.com ");

Cookie. setpath ("/");

Cookiestore. addcookie (cookie );

// Set Storage

Httpclient. setcookiestore (cookiestore );

3.8 HTTP status management and execution Context

During HTTP request execution, httpclient adds the following State management-related objects to the execution context:

  • 'Http. cookiespec-Registry ': The cookiespecregistry instance represents the actual cookie standard registry. The value of this attribute is set in the local content, which takes precedence over the default value.

  • 'Http. Cookie-spec ': The cookiespec instance represents the actual cookie specification.

  • 'Http. Cookie-origin': The cookieorigin instance represents the details of the real source server.

  • 'Http. Cookie-store': The cookiestore instance represents the real cookie storage. Set the value of this attribute in the local content to take precedence over the default value.

The local httpcontext object can be used to customize HTTP status management content and check its status before the request is executed or after the request is executed:

Httpclient = new defaulthttpclient ();

Httpcontext localcontext = new basichttpcontext ();

Httpget = new httpget ("http: // localhost: 8080 /");

Httpresponse response = httpclient.exe cute (httpget, localcontext );

Cookieorigin = (cookieorigin) localcontext. getattribute (

Clientcontext. cookie_origin );

System. Out. println ("Cookie origin:" + cookieorigin );

Cookiespec = (cookiespec) localcontext. getattribute (

Clientcontext. cookie_spec );

System. Out. println ("Cookie spec used:" + cookiespec );

3.9 state management for each user/thread

We can use independent local execution context to manage the status of each user (or each thread. Defining the cookie specification registry and cookie storage in the local content will take precedence over those set at the HTTP client level.

Httpclient = new defaulthttpclient ();

// Create a local instance of the cookie store

Cookiestore = new basiccookiestore ();

// Create local HTTP Content

Httpcontext localcontext = new basichttpcontext ();

// Bind the custom cookie store to the local content

Localcontext. setattribute (clientcontext. cookie_store, cookiestore );

Httpget = new httpget ("http://www.google.com /");

// Pass the local content as a parameter

Httpresponse response = httpclient.exe cute (httpget, localcontext)

Httpclient HTTP Status Management

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.