Apache client Instructions for use chapter I (part I.)

Source: Internet
Author: User
Tags html form

The first chapter. Basis

1.1 Execution of the request

The most important function of httpclient is to execute the HTTP method. The HTTP method is executed once to include the interaction of one or more HTTP requests and HTTP responses, usually within httpclient. The programmer only needs to provide a request object for execution, The httpclient sends the request path to the target server and obtains the corresponding response object, or throws an exception if the execution is unsuccessful.

The HttpClient API's only entry point is the HttpClient interface.

The following is a simple example of a request execution process

Closeablehttpclient httpclient = Httpclients.createdefault (); HttpGet httpget = new HttpGet ("http://localhost"); Closeablehttpresponse response = Httpclient.execute (httpget); try {<...>} finally {resopnse.close ();}

1.1.1 HTTP Requests

All HTTP requests have a request line consisting of a method name, a request path, and an HTTP protocol version.

HttpClient supports all HTTP methods defined by http/1.1, specifically; Get,head,post,put,delete,trace and options. Each type of method corresponds to a specific class: Httpget,httphead,httppost,httpput,httpdelete, HttpTrace and Httpoptions.

Request-uri is a Uniform Resource locator that is used to request a unique. The HTTP request path is provided by protocol, hostname, optional port number, resource path, optional query parameters and optional segment (which can be understood as the ID of the page element and can be directly redirected).

HttpGet httpget = new HttpGet ("http://www.google.com/searche?h1=en&q=httpclient&btnG=Google+Search&aq= F&oq= ");

HttpClient provides the UriBuilder tool class to easily create and modify request paths

Uri uri = new UriBuilder (). SetScheme ("http"). Sethost (". SetPath (" Search "). Setparameter (" Q "," HttpClient "). Setparameter ("btng", "Google Search"). Setpatameter ("AQ", "F"). Setparameter ("OQ", ""). Build (); HttpGet httpget = new HttpGet (URI); System.out.println (Httpget.geturi ());

Output

http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq=

1.1.2 HTTP Response

An HTTP response is information that is returned to the client when the request information is received and interpreted by the server. The first line of the message consists of the protocol and version followed by the status code and the reason for the value.

HttpResponse response = new Basichttpresponse (HTTPVERSION.HTTP_1_1,HTTPSTATUS.SC_OK, "OK"); System.out.println (Response.getprotocolversion ()); System.out.println (Response.getstatusline (). Getstatuscode ()); System.out.println (Response.getstatusline (). Getreasonphrase ()); System.out.println (Response.getstatusline (). toString ());

Output

http/1.1200okhttp/1.1 OK

1.1.3 Processing message header information

An HTTP message contains multiple headers that describe a message's properties such as: Content length,content type, and so on. HttpClient provides methods for retrieving, adding, removing, and enumerating header information.

HttpResponse response = new Basichttpresponse (HTTPVERSIOIN.HTTP_1_1,HTTPSTATUS.SC_OK, "OK"); Response.AddHeader (" Set-cookie "," c1=a;path=/;d omain-localhost ") Response.AddHeader (" Set-cookie "," c2=b;path=\ "/\", c3=c;domain=\ " Localhost\ ""); Header H1 = Response.getfirstheader ("Set-cookie"); SYSTEM.OUT.PRINTLN (H1); Header H2 = Response.getlastheader ("Set-cookie"); System.out.println (H2); Header[] hs = response.getheaders ("Set-cookie"); System.out.println (hs.length);

Output

set-cookie:c1=a;path=/;d omain=localhostset-cookie:c2=b;path= "/", c3=c;domain= "localhost" 2

The most efficient way to get all the header information for a given type is to use the Headeriterator interface.

HttpResponse response = new Basichttpresponse (Httpversion.http_1_1,httpstatus.sc, "OK"); Response.AddHeader (" Set-cookie "," c1=a;path=/;d omain-localhost ") Response.AddHeader (" Set-cookie "," c2=b;path=\ "/\", c3=c;domain=\ " Localhost\ ""); Headeriterator it = response.headeriterator ("Set-cookie"), while (It.hasnext) {System.out.println (It.next ());}

Output

Set-cookie:c1=a; path=/; Domain=localhostset-cookie:c2=b; Path= "/", c3=c; domain= "localhost"

Also provides an easy way to parse an HTTP message for a single header element

HttpResponse response = new Basichttpresponse (Httpversion.http_1_1,httpstatus.sc, "OK"); Response.AddHeader (" Set-cookie "," c1=a;path=/;d omain-localhost ") Response.AddHeader (" Set-cookie "," c2=b;path=\ "/\", c3=c;domain=\ " Localhost\ ""); Headerelementiterator it = new Basicheaderelementiterator (Response.headeriterator ("Set-cookie")); while (It.hasNext (    ) {HeaderElement Elem = it.nextelement ();    System.out.println (Elem.getname () + "=" + Elem.getvalue ());    namevaluepair[] params = elem.getparameters ();    for (int i = 0; i < params.length; i++) {System.out.println ("" + params[i]); }}

Output

C1 = APATH=/DOMAIN=LOCALHOSTC2 = BPATH=/C3 = Cdomain=localhost

1.1.4 HTTP Entity

An HTTP message can carry a content entity that is related to a request or response. An entity is optional and can be found in some requests or responses. The HTTP specification defines two request methods that contain entities: Post and put. The response typically contains a content entity. In some cases exceptions such as: Heade method Response, 204 not content,304 not modified,205 Reset The content of these responses.

HttpClient the entity into three categories based on the source of the content:

Streamed: Content is received from the stream or generated during the run. Specifically, this class contains entities that receive a response from the HTTP. Streamed entities are usually non-repeatable.

Self-contained: stored in memory, independent of HTTP connections or other entities. This type of entity is often used in HTTP request encapsulation.

Wrapping: Content from other entities

For connection management, these differences are important when you derive a stream from an HTTP response.

1.1.4.1 repeatable Entities

The repetition of an entity means that his content can be read multiple times. Only possible for self contained (such as bytearrayentity or stringentity)

1.1.4.2 using HTTP Entities

Because the entity can represent both binary and character content, there is encoding support.

The entity is created when the content is encapsulated during the execution of the request, or the request succeeds, and the response body is used to return the results to the client.

Reads from the entity, an input stream obtained through the Httpentity#getcontent () method, which returns a Java.io.InputStream, or Httpentity#writeto (Ouputstream) Method provides an output stream that writes all content to the provided stream.

When an entity has been received through an incoming message, Httpentity#getcontenttype () and Httpentity#getcontentlength () Methods can be used to read common meta-data such as Content-type and content-length head mentality (if they exist). Since the Content-type header can contain character encodings, httpentity#getcontentencoding The () method is used to read this part of the information. When the header does not exist, the length returns-1, and the content type returns NULL. When the Content-type head is present, the header object is returned.

When creating an entity for output messages, the metadata for this write entity must be provided by the entity's creator.

Stringentity myentity = new Stringentity ("Important Message", Contenttype.create ("Text/plain", "UTF-8")); System.out.println (Myentity.getcontenttype ()); System.out.println (Myentity.getcontentlength ()); System.out.println (entityutils.tostring (myentity)); System.out.println (Entityutils.tobytearray (myentity). length);

Output

Content-type:text/plain; Charset=utf-817important Message17

1.1.5 confirm release of underlying resources

In order to ensure proper release of system resources, you must close the entity's associated stream or the response itself.

closeablehttpclient httpclient =  Httpclients.createdefault (); Httpget httpget = new httpget ("http://localhost/"); Closeablehttpresponse response = httpclient.execute (HttpGet);try {     Httpentity entity = response.getentity ();     if (entity != null) {         inputstream instream = entity.getcontent ();         try {             //do something useful        }  Finally {            instream.close ();         }    }} finally {     response.close ();} 

The difference between closing the content stream and closing the response is that the former attempts to keep the underlying connection active by consuming the entity content, while the latter shuts down and discards the connection immediately.

Note that the Httpentity#writeto (OutputStream) method also requires that the system resources be freed when the content is completely written out. If the method contains a call to Httpentity#getcontent () The resulting Java.io.InputStream instance should also close the stream in the finally code block.

When using the stream entity, you can use the Entityutils#consume (httpentity) method to ensure that the entity content is completely consumed and that the underlying stream has been closed.

In this case, when only a small portion of the response content needs to be retrieved, the consumption of the remainder of the reuse connection is too expensive, which can be done by closing the response to terminate the stream.

Closeablehttpclient httpclient = Httpclient.createdefault (); HttpGet httpget = new HttpGet ();    Closeablehttpresponse response = Httpclient.execute (httpget); try {httpentity entity = response.getentity ();        if (Entity! = null) {InputStream instream = entity.getcontent ();        int byteone = Instream.read ();        int bytetwo = Instream.read (); Do not need the rest}} finally {Response.close ();}

The connection will not be reused, and all referenced resources will be released correctly.

1.1.6 Consuming entity content

The

Consume entity content is recommended using the Httpentity#getcontent () or Httpentity#writeto (OutputStream) method. The httpclient is also equipped with a Entityutils class that provides several static methods to make it easier to read the contents or information of an entity. In addition to reading the Java.io.InputStream directly, The body portion of the content can be retrieved from a string or byte array by means of the class. However, it is strongly discouraged to use entityutils unless the response is from a trusted HTTP server and is known to have a length limit.

Closeablehttpclient httpclient = httpclients.createdefault (); Httpget httpget = new httpget (); Closeablehttpresponse response = httpclient.execute (HttpGet);try {     Httpentity entity = response.getentity ();     if (entity != null) {         long len = entity.getcontentlength ();         if (len != -1 && len < 2048)  {            system.out.println ( Entityutil.tostring (entity));        } else {             // Steam content out         }    }} finally {     Response.close ();} 

In some cases, the entity content needs to be read more than once. This is required by some means to replace the entity content through memory or disk. The simplest approach is to use the Bufferedhttpentity class to encapsulate the original entity. This allows the contents of the original entity to be read into the memory buffer.

Closeablehttpresponse response = <...>; httpentity entity = response.getentity (), if (entity! = null) {entity = new bufferedhttpentity (entity);}

1.1.7 Production Entity Content

HttpClient provides multiple classes of efficient outgoing content over HTTP connections. Instances of these classes can correlate the entities that the request contains, such as post and put, to

Mount the outgoing HTTP request. HttpClient provides multiple classes as containers for most data such as strings, byte arrays, input streams, and files: stringentity,bytearrayentity,inputstreamentity, and fileentity.

File File = new file ("Somefile.txt"); fileentity entity = new Fileentity (file,contenttype.create ("Text/plain", "UTF-8"); HttpPost HttpPost = new HttpPost (""); httppost.setentity (entity);

Note that inputstreamentity is not repeatable because it can only be read once from the underlying data stream. In general, it is recommended to implement a custom httpentity class.

1.1.7.1 HTML Form

Many programs need to emulate HTML form submission operations, such as logging in to a Web application or committing input data. HttpClient provides entity class urlencodedformentity to help implement this process.

list<namevaluepair> formparams = new arraylist<namevaluepair> (); Formparams.add (New BasicNameValuePair (" Param1 "," value1 ")); Formparams.add (New Basicnamevaluepair (" param2 "," value2 ")); urlencodedformentity entity = new urlencodedformentity (formparams,consts.utf_8); HttpPost HttpPost = new HttpPost (); httppost.setentity (entity);

The urlencodedformentity instance will call URL encoding to encode the parameter and produce the following:

Param1=value1&param2=value2

1.1.7.2 content chunking

It is generally recommended to select the appropriate transmission encoding by httpclient based on the properties of the transmitted HTTP message. However, you can also set the httpentity#setchunked () True tells HttpClient that the block takes precedence over the encoding. HttpClient only use this tag as a hint. This value is ignored when the HTTP protocol version used does not support chunked encoding. For example, http/1.0.

stringentity entity = new Stringentity ("Important messae", Contenttype.create ("Plain/text", Consts.utf_8)); Entity.setchunked (TRUE); HttpPost HttpPost = new HttpPost (); httppost.setentity (entity);

1.1.8 Response Processing

The simplest and most convenient way to handle a response is to use the ResponseHandler interface, which contains Handleresponse (httprespinse response) Method. This method does not require the user to worry about connection management. When using Responsehandler,httpclient, the management and deallocation of automatic connections is performed regardless of whether the request executes successfully or causes an exception.

Closeablehttpclient httpclient = httpclients.createdefault (); Httpget httpget = new httpget (); Responsehandler<myjsonobject> rh = new responsehandler<myjsonobject> () {     public jsonobject handleresponse (final httpresponse response)   throws ioexception{        statusline statusline =  response.getstatusline ();         httpentity entity =  response.getentity ();         if (Statusline.getstatuscode ()   &GT;=&NBSP;300) {            throw new  Httpresponseexception (Statusline.getstatuscode (),  statusline.getreasonphrase ());         }        if (entity == null) {   &nbsP;         throw new clientprotocolexception ("Response  contains no content ");        }         gson gson = new gsonbuilder (). Create ();         contenttype contenttype = contenttype.getordefault (Entity);         charset charset = contenttype.getcharset ();         reader reader = new inputstreamreader ( Entity.getcontent (), CharSet);         return gson.fromjson (reader, Myjsonobject.class);    }}; Myjsonobject myjson = client.execute (HTTPGET,RH);



Apache client Instructions for use chapter I (part I.)

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.