HttpClient-01 Basic Concepts

Http protocol should be the most important Internet protocols. The continued growth of web services, networkable household appliances and so on in succession and expand the Http protocol, the direction of the outside of the browser development.

While providing some basic methods of jdk java.net package, to access network resources via http protocol, but in most scenarios, it is flexible and powerful enough. HttpClient is committed to fill this gap, it can provide an effective, new, feature-rich package to achieve the http client

The following example is a simple request:

    @Test
     public void test01() throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet("http://www.baidu.com/");
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            System.out.println(response);
        } catch (Exception e) {

        } finally {
            response.close();
        }
    }

1.1.1. HTTP request

All Http request has a request line (request line), including the method name, and Http request URI version number.

HttpClient supports HTTP / 1.1 This version of the definition of all Http methods: GET, HEAD, POST, PUT , DELETE, TRACE and OPTIONS. For each http method, HttpClient defines a corresponding class:
HttpGet, HttpHead, HttpPost, HTTP PUT, HttpDelete, HttpTrace and HttpOpquertions.

Request-URI or Uniform Resource Locator, Http request to indicate resources. Http request URIs include a protocol name, host name, host port (optional), resource path, Query (optional) and clip information (optional). 

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

HttpClient provides URIBuilder tools to simplify the creation and modification of URIs.

     @Test
     public void test02() throws Exception {
        URI uri = new URIBuilder()
         .setScheme("http")
         .setHost("www.google.com")
         .setPath("/search")
         .setParameter("q", "httpclient")
         .setParameter("btnG", "Google Search")
         .setParameter("aq", "f")
         .setParameter("oq", "")
         .build();

        HttpGet httpget = new HttpGet(uri);

        System.out.println(httpget.getURI());

    }

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

1.1.2. HTTP响应

服务器收到客户端的http请求后,就会对其进行解析,然后把响应发给客户端,这个响应就是HTTP response.HTTP响应第一行是HTTP版本号,然后是响应状态码和响应内容。

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());

1.1.3. 消息头

一个Http消息可以包含一系列的消息头,用来对http消息进行描述,比如消息长度,消息类型等等。HttpClient提供了API来获取、添加、修改、遍历消息头。

HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    response.addHeader("Set-Cookie", "c1=a; path=/; domain=yeetrack.com");
    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);

The most effective access to the specified type of message header or a method using HeaderIteratoran interface.

HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
response.addHeader("Set-Cookie", "c1=a; path=/; domain=yeetrack.com");
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());
}

HeaderIterator also provides a convenient way, the message parsing into individual Http header message element.

HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
response.addHeader("Set-Cookie", "c1=a; path=/; domain=yeetrack.com");
response.addHeader("Set-Cookie", "c2=b; path=\"/\", c3=c; domain=\"yeetrack.com\"");
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]);
    }
}

1.1.4. HTTP entity

Http http message may carry an entity, the entity can be either http http request, or may be a http response. Http entity can be found at http request or response in some, but not necessarily. Http specification defines two requests comprising: POST and PUT. HTTP response typically comprises a content entity. Of course, this rule there are exceptions, such as response Head method, no content 204, 304 or 205 does not modify the contents of resource resetting.

HttpClient according to different sources, divided in three different entities Http content.

  • streamed:  the Http to receive content by streaming, streamed this class contains substantial contents obtained from http response. Generally, streamed entity is not repeatable.
  • -Contained Self:  Self-Contained types of solid content is typically repeatable. This type of entity is typically used to close the http request.
  • wrapping:  This type of content is obtained from http another entity.

1.1.4.1. Repeatable entity

Entity is a reproducible, which means that it contains the content may be read many times. This entity only once, read many self contained (self-contained) can be done (such as ByteArrayEntityor StringEntity).

1.1.4.2. Use Http entity

Due to a Http entity can represent both binary content, but also represents the textual content, so Http entity to support the character encoding (in order to support the latter, that is, text content).

When you need to perform a full content or Http request Http request has been successful, the server to send a response to the client, Http entity will be created.

If the contents read from Http entity, we can use the HttpEntityclass getContentmethods to obtain the input stream entities ( java.io.InputStream), or by HttpEntityclass writeTo(OutputStream)methods to obtain an output stream, this method will all be written to a given content stream .
When the entity class has been accepted, we can use HttpEntitythe class getContentType()and getContentLength()reading methods Content-Typeand Content-Lengthtwo header message (if any). Because Content-Typecomprising character encoding mime-types, such as text / plain or text / html, HttpEntityclass getContentEncoding()is to read the code. If the header is not present, getContentLength()it returns -1, getContentType()returns NULL. If Content-Typeinformation exists, it will return a Headerclass.

When creating Http entity to send a message, you need to additional meta information.

  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);

1.1.5. Ensure that the underlying connection is released resources

To ensure that system resources are properly released, we either manage content flow Http entity, either close Http response.

CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet("http://www.baidu.com/");
        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();
        }

Close Close Http Http solid content stream and in response to the difference that the former is related to maintaining consumed via http Http substantial contents, which then closes immediately discarded http connection.

1.1.6. HTTP entity content consumption

HttpClient is recommended to use HttpEntitya getConent()method or HttpEntitya writeTo(OutputStream)way to consume content Http entity. HttpClient also provides EntityUtilsthis class, this class provides static methods can be more easily read the content and information Http entities. And in a java.io.InputStreammanner to read the contents of the stream as compared to the method provided may be read EntityUtils Http entity in the form of a string or byte array. However, it is strongly not recommended to use EntityUtilsthis class, unless the response issued by the target server is trusted, and http response length entity does not become too large.

CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet("http://www.yeetrack.com/");
    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(EntityUtils.toString(entity));
            } else {
                // Stream content out
            }
        }
    } finally {
        response.close();
    }

In some cases, we hope to repeat Http read the contents of the entity. This requires the entity Http content caching in memory or disk. The easiest way is to Http converted to the Entity BufferedHttpEntity, so the original content Http entity put into the buffer memory. Later we will content BufferedHttpEntity can be read repeatedly.

 CloseableHttpResponse response = <...>
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        entity = new BufferedHttpEntity(entity);
    }

1.1.7. Creating HTTP entity content

Providing a HttpClient classes substantial contents can be output efficiently Http connection via http. These classes of common data types HttpClient cover provided, such as String, byte array input stream, and file types: StringEntityByteArrayEntity, InputStreamEntity, FileEntity.

 File file = new File("somefile.txt");
        FileEntity entity = new FileEntity(file, ContentType.create("text/plain", "UTF-8"));

        HttpPost httppost = new HttpPost("http://www.yeetrack.com/action.do");
        httppost.setEntity(entity);
    }

Note that since InputStreamEntityonly the data stream read from a lower layer, so it is not repeated. Recommended by inherited HttpEntitythis self-contained classes to customize HttpEntity class, rather than directly using InputStreamEntitythis class. FileEntityIs a good starting point (FileEntity is inherited HttpEntity).

1.7.1.1. HTML form

Many applications need to simulate the process of submitting Html form, for example, a landing site or the content of the input submitted to the server. HttpClient provides UrlEncodedFormEntitythis class to help achieve 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("http://www.yeetrack.com/handler.do");
    httppost.setEntity(entity);

UrlEncodedFormEntityExamples of uses so-called Url coded way we encode parameters, the result is as follows:

    param1=value1&param2=value2

1.1.7.2. Content block

In general, it is recommended to make their own HttpClient to select the most appropriate transfer encoding characteristics according Http messaging. Of course, if you have to manual control it is also possible, by setting HttpEntitya setChunked()to true. Please note: HttpClient this parameter will only be seen as a suggestion. If Http versions (such as http 1.0) does not support the content block, then this parameter is ignored.

        StringEntity entity = new StringEntity("important message",
                ContentType.create("plain/text", Consts.UTF_8));
        entity.setChunked(true);
        HttpPost httppost = new HttpPost("http://www.yeetrack.com/acrtion.do");
        httppost.setEntity(entity);

Guess you like

Origin www.cnblogs.com/deityjian/p/11424089.html