Basic use of HttpClient

Source: Internet
Author: User

Introduction to basic use of httpclient

HttpClient is a tool that Apache provides to handle HTTP requests, response operations in Java, because the JDK's own API is not very friendly to the HTTP protocol, it is not very convenient to use, plus these days there are just a small project to use, So I learned the basic use of httpclient and sorted out the notes of the learning process.

HTTP request

As we know, an HTTP request contains a few parts of the content, the first is the request line (including the request method, the URI of the request, the version of the HTTP protocol), the request header (a number of key-value pairs), and the optional request body (often stored in the post, there is no content in the get)

HttpClient has encapsulated each of these parts, so let's take a look at the specific operations in detail.

HTTP request Line

An HTTP request line corresponding to the content has been mentioned above, here do not do too much narration, in HttpClient, an HTTP request line corresponding to the class, the RequestLine specific operation as shown in the following code:

    // 创建一个GET对象    getnew HttpGet("http://www.baidu.com");    // 获得请求行对象    get.getRequestLine();    // 获得请求方法    System.out.println(statusLine.getMethod());    // 获得请求URI    System.out.println(statusLine.getUri());    // 获得HTTP版本协议    System.out.println(statusLine.getProtocolVersion());

The corresponding output results are as follows:

GEThttp://www.baidu.comHTTP/1.1

As you can see, httpclient encapsulates a request line for an HTTP request through the Requestline object.

Request Header

In HTTP, HTTP header information contains a lot of content, such as Content-type, Set-cookie, and so on, here we demonstrate a simple small case, note that the header information here includes the request and the response, they are only the corresponding key value pairs and the meaning of the difference, The form is consistent, as shown in the following code:

    / * Set header information via header object * /Header Header = new Basicheader ("Content-type","Text/plain");Header header1 = new Basicheader ("Set-cookie","C1=A; path=/; Domain=localhost ");Response. AddHeader(header);Response. AddHeader(Header1);    / * Get specific header information * /Header Respheader = response. Getfirstheader("Content-type");System. out. println(Respheader. GetName() +" : "+ Respheader. GetValue());Respheader = response. Getfirstheader("Set-cookie");System. out. println(Respheader. GetName() +" : "+ Respheader. GetValue());     / * Access all header information via iterators * /Headeriterator iterator = response. Headeriterator();while (iterator. Hasnext()) {Header tmp = iterator. Nextheader();System. out. println(TMP. GetName() +" : "+ tmp. GetValue());}/ * Get all the elements in a message and their values * /Headerelementiterator Iterator1 = new Basicheaderelementiterator (response. Headeriterator("Set-cookie"));while (Iterator1. Hasnext()) {headerelement element = Iterator1. Nextelement();System. out. println(element. GetName() +" : "+ element. GetValue());Namevaluepair[] Params = element. GetParameters();for (Namevaluepair n:params) {System. out. println(n. GetName() +" : "+ N. GetValue());}    }

The corresponding output results are as follows:

Content-type : text/plainSet-Cookie : c1=a; path=/; domain=localhostContent-type : text/plainSet-Cookie : c1=a; path=/; domain=/domain : localhost
HTTP entity

In an HTTP, it usually involves entities, entity, that is, the real content of the request/response, in the request, usually put and post will contain the entity, and in the response, the general will contain an entity, used as a carrier to return information on the server.

In HttpClient, there are three forms of the entity, and the content and specific meanings are as follows:

    1. Streamed: from the byte stream, especially from the response, which is usually non-repeatable
    2. Self-contained: comes from memory or is not related to a connection, usually repeatable, typically used to encapsulate an HTTP request
    3. Wrapping: From other entity

It is important to note that the form of the entity does not imply the concrete type of the entity, that is to say, the entity form above is only a conceptual understanding, the specific type can be: stringentity, bytearrayentity, Inputstreamentity, Fileentity and so on, basically these types all see the meaning of the name, so here do not do too much explanation, specific can refer to the Official Handbook

Here's a simple demonstration of using stringentity to pass and receive data

    / * Set a String type of entity * /stringentity entity =NewStringentity ("Hello"); Response.setentity (entity);/ * Receive a String type of entity * /Httpentity entity1 = response.getentity ();if(Entity1! =NULL){//through the Entityutils tool to obtain        //system.out.println (entityutils.tostring (entity1));        //stream to get dataInputStream InputStream = Entity1.getcontent ();byte[] data =New byte[Inputstream.available ()];        Inputstream.read (data); System. out. println (NewString (data,0, data.length)); Inputstream.close ();//Remember to close the resources here}
HTTP response lines for HTTP responses

As we know, the HTTP response contains a response line (HTTP version, status Code, Status code Interpretation) response header (see the Request header section above) and the corresponding entity (see the entity section above)

Next, let's look at the response line and the use of the HttpResponse object.

Create a httpresponse httpresponse response = new Basichttpresponse (httpversion. HTTP_1_1, Httpstatus. SC_OK,"OK");Get the corresponding status line statusline StatusLine1 = response. Getstatusline();HTTP protocol version System. out. println(statusLine1. Getprotocolversion());Response result System. out. println(statusLine1. Getstatuscode());Explanation of the response result System. out. println(statusLine1. Getreasonphrase());

The corresponding results are as follows

HTTP/1.1200ok
Send/Receive HTTP requests

The above is mainly about HTTP requests and the content of the response, and then see how httpclient is sending HTTP requests and receiving requests

    // 创建一个HttpClient对象    client = HttpClients.createDefault();    // 发送请求并且获得返回的结果    client.execute(request);
Summarize

This section focuses on the use of httpclient, including the use of HTTP request objects, the use of HTTP response objects, and how to send HTTP requests and get the results returned

Basic use of HttpClient

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.