Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ The principle Httpclient4.4 (execution request)     - Why JavaScript basic types can invoke methods (Programming)

- Java implementation chain store binary tree (Programming)

- How x2g0 install Remote Desktop on Linux VPS (Server)

- CentOS7 Kubernetes used on container management (Server)

- Comparison of one-time transaction and CTE insert data (Database)

- Linux Beginner Guide: Installing packages on Ubuntu and Fedora (Linux)

- HBase table data processing tab (Database)

- How to use scientific data Docker quickly configure the development environment (Server)

- How to install Linux Kernel 4.4 on Ubuntu (Linux)

- How to limit network bandwidth usage in Linux (Linux)

- RAID configuration and management under linux (Server)

- Java factory pattern (Factory mode) (Programming)

- Shell programming entry (Programming)

- Sudo and Root Account in Ubuntu related (Linux)

- Configuring s3c-linux-2.6.28.6-Real6410 appears Unable to find the QT3 installation (Linux)

- CentOS installation of the ftp (Linux)

- Help you make Git Bisect (Linux)

- JQuery implements the same content merge cells (Programming)

- KVM QEMU virtual machine installation configuration under CentOS (Linux)

- dd command: do hard disk IO performance test (Linux)

 
         
  The principle Httpclient4.4 (execution request)
     
  Add Date : 2018-11-21      
         
         
         
  Apache Httpclient based java BIO achieve, also based on apache HttpCore project. His most basic function is to perform HTTP methods. The main entrance of HttpClient HttpClient API is an interface, look at this example:

package httpclienttest;
 
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
 
public class T1 {
    public static void main (String [] args) {
        HttpGet httpget = new HttpGet ( "http://www.linuxidc.com");
        try (CloseableHttpClient httpclient = HttpClients.createDefault ();
                CloseableHttpResponse response = httpclient.execute (httpget);) {
            System.out.printf ( "content type:% s", response.getEntity () getContentType ().);
        } Catch (Exception e) {
            e.printStackTrace ();
        }
}

1. HTTP request

All http requests are: method name, the request url, HTTP protocol components. All methods HttpClient supports HTTP / 1.1 support: GET, HEAD, POST, PUT, DELETE, TRACE and OPTIONS, HttpClient in both a specific class corresponding: HttpGet, HttpHead, HttpPost, HttpPut, HttpDelete, HttpTrace and HttpOptions.

HTTP request URI includes the protocol, hostname, optional port, resource path, an optional query conditions. In the following example:

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

HttpClient provides URIBuilder generic class to create or modify a request URI, such as for example:

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

2. HTTP response

HTTP response is an HTTP request is sent to the server to handle the response to the client's message. Response to the first line is the agreement with the protocol version number, followed by a numeric status code and the number of text messages, to see what the results of sample demonstrates:

package httpclienttest;
 
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.message.BasicHttpResponse;
 
public class T2 {
    public static void main (String [] args) {
        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 ().);
    }
}
 

The output is:
 
HTTP / 1.1
200
OK
HTTP / 1.1 200 OK
 

3. HTTP header

HTTP header (header) contains information about multiple messages described in, for example: content length, content types. Methods are provided HttpClient to retrieve, add, delete, and enumerate other operations. Example:

package httpclienttest;
 
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.message.BasicHttpResponse;
 
public class T3 {
    public static void main (String [] args) {
        HttpResponse response = new BasicHttpResponse (HttpVersion.HTTP_1_1,
                HttpStatus.SC_OK, "OK");
        response.addHeader ( "Set-Cookie", "c1 = a; path = /; domain = 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 = /; domain = localhost
Set-Cookie: c2 = b; path = "/", c3 = c; domain = "localhost"
2
 

More efficient way is through the interface HeaderIterator get all header information, for example:

package httpclienttest;
 
import org.apache.http.HeaderIterator;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.message.BasicHttpResponse;
 
public class T4 {
    public static void main (String [] args) {
        HttpResponse response = new BasicHttpResponse (HttpVersion.HTTP_1_1,
                HttpStatus.SC_OK, "OK");
        response.addHeader ( "Set-Cookie", "c1 = a; path = /; domain = 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 = localhost
Set-Cookie: c2 = b; path = "/", c3 = c; domain = "localhost"
 

He also provides a more convenient way to parse HTTP header in the message and get a separate header elements, for example:

package httpclienttest;
 
import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.message.BasicHttpResponse;
 
public class T5 {
    public static void main (String [] args) {
        HttpResponse response = new BasicHttpResponse (HttpVersion.HTTP_1_1,
                HttpStatus.SC_OK, "OK");
        response.addHeader ( "Set-Cookie", "c1 = a; path = /; domain = localhost");
        response.addHeader ( "Set-Cookie", "c2 = b; path = \" / \ ", c3 = c; domain = \" localhost \ "");
        HeaderElementIterator = 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 = a
path = /
domain = localhost
c2 = b
path = /
c3 = c
domain = localhost
 

4. HTTP Entity

HTTP message can carry the request or response content-related entity, it is only optional, and can be found in some request or response. Request message using the entity for the entity enclosing request, HTTP specification defines two entity enclosing request methods: POST and PUT. Response is usually a packaging entity, of course, there are exceptions!

HttpClient distinguishes three entities, according to their content source:

streamed (stream): content received from the stream. Flow entity is not repeatable.


self-contained (self-contained): Content in memory or obtained from independent connection or other entities. Self-contained entities are usually reproducible. This type of entity is usually used for entity enclosing request.


When the contents of the outflow from the HTTP response, for connection management (connection management) This distinction is very important. For the requesting entity was created by the application and only use HttpClient to send this distinction for streamed with self-contained little significance. In this case, we recommend that the non-repeatable entities as streamed, those repeatable as self-contained.

4.1 repeatable entity

Being an entity can be repeated, it means that content can be read many times. This is the only possible self-contained entity (eg: ByteArrayEntity or StringEntity).

4.2 Use HTTP entity

Because the entity can represent binary and character content, which is supported character sets (to support the latter, that is, text).

Read from the entity content, possibly through HttpEntity's getContent () method to retrieve the input stream, it returns a java.io.InputStream, or may provide an output stream of argument as HttpEntity writeTo (OutputStream) method will return all content written to a given stream.

When an entity receives an incoming message, HttpEntity of getContentType method and getContentLength method can be used in a read request header metadata: Content-Type and Content-Length (if they are available). Since the Content-Type header can contain such a MIME type of character set like text / plain or text / html (coding), HttpEntity of getContentEncoding () method is used to read this information. If the header is not available, the length will return -1 and content type is NULL. If the Content-Type header is available, the Header object will return.

When creating an entity an output message, the data is provided by the creator of the entity, for example:
 
package httpclienttest;
 
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
 
public class T6 {
    public static void main (String [] args) throws Exception {
        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);
    }
}
 

The output is:
 
Content-Type: text / plain; charset = UTF-8
17
important message
17
 

5. Make sure that the release of low-level resources

In order to secure the release of system resources, you must close related entities or content stream response itself:

package httpclienttest;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Stream;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
 
public class T7 {
    public static void main (String [] args) {
        CloseableHttpClient httpclient = HttpClients.createDefault ();
        HttpGet httpget = new HttpGet ( "http://ifeng.com");
        // Use java7 syntax, automatically calls the close () method, so there is no call display
        try (CloseableHttpResponse response = httpclient.execute (httpget)) {
            HttpEntity entity = response.getEntity ();
            try (BufferedReader reader = new BufferedReader (new InputStreamReader (
                    entity.getContent (), StandardCharsets.UTF_8))) {
                Stream < String> sm = reader.lines ();
                sm.forEach (System.out :: println);
            }
        } Catch (Exception e) {
            e.printStackTrace ();
        }
    }
}
 

Close Close content stream and the difference between the response is that the former tried to keep the contents of the consumer entity basic connection is alive, which closes the connection and discarded! Note: Once the entity has been completely written, HttpEntity of writeTo (OutputStream) method must also ensure that system resources are released. If you call HttpEntity the getContent () method to obtain an instance of java.io.InputStream stream, and also to the final closing and release of resources.

When a work flow entities, EntityUtils of consume (HttpEntity) method to ensure that the content of the entity is completely consumed, the background and automatically close the stream to free up resources.

A kind of rare cases, the entity's response to the content request only a small part needs to be retrieved, and the rest do not need, and consume the remaining contents of another performance loss, resulting in a high reuse connections. In this case, you can just close response to terminate the flow of content! In the following example:

package httpclienttest;
 
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
 
public class T8 {
    public static void main (String [] args) {
        CloseableHttpClient httpclient = HttpClients.createDefault ();
        HttpGet httpget = new HttpGet ( "http://ifeng.com");
        try (CloseableHttpResponse response = httpclient.execute (httpget)) {
            HttpEntity entity = response.getEntity ();
            if (entity! = null) {
                InputStream instream = entity.getContent ();
                int byteOne = instream.read ();
                int byteTwo = instream.read ();
                System.out.printf ( "% d,% d", byteOne, byteTwo);
                // Instream remaining contents do not need it! Direct response Close
            }
        } Catch (Exception e) {
            e.printStackTrace ();
        }
    }
}
 

Such connections will not be reused, but resources at all levels will be released!

6. Consumption substantial contents

Consume substantial contents of the recommendation is to use HttpEntity getContent () or HttpEntity of writeTo (OutputStream) method. HttpClient is also equipped with EntityUtils class, which provides several static methods to make reading easier entity content and information, rather than reading java.io.InputStream. EntityUtils through these static methods to retrieve the entire contents of the body to which the string / byte array. Anyway, it is strongly recommended not to use EntityUtils, unless a response from a credible entity generates an HTTP server and know the finite length. Example:
 
package httpclienttest;
 
import java.nio.charset.StandardCharsets;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
 
public class T9 {
    public static void main (String [] args) {
        CloseableHttpClient httpclient = HttpClients.createDefault ();
        HttpGet httpget = new HttpGet ( "http://www.ifeng.com/");
        try (CloseableHttpResponse response = httpclient.execute (httpget)) {
            HttpEntity entity = response.getEntity ();
            if (entity! = null) {
                System.out.println (EntityUtils.toString (entity, StandardCharsets.UTF_8));
            }
        } Catch (Exception e) {
            e.printStackTrace ();
        }
    }
}
 

In some cases, you may want to read the contents of more than one entity. In this case, the entity content must be buffered to some extent, both in memory and disk. The easiest way is to wrap the original entity through BufferedHttpEntity class, which will make the content of the original entity into the memory buffer. Example:
 
package httpclienttest;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Stream;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
 
public class T10 {
    public static void main (String [] args) {
        CloseableHttpClient httpclient = HttpClients.createDefault ();
        HttpGet httpget = new HttpGet ( "http://www.ifeng.com/");
        try (CloseableHttpResponse response = httpclient.execute (httpget)) {
            HttpEntity entity = response.getEntity ();
            if (entity! = null) {
                // Buffer entity, reusable
                entity = new BufferedHttpEntity (entity);
                try (BufferedReader reader = new BufferedReader (new InputStreamReader (
                        entity.getContent (), StandardCharsets.UTF_8))) {
                    Stream < String> sm = reader.lines ();
                    sm.forEach (System.out :: println);
                }
                System.out.println ( "read a second time!");
                try (BufferedReader reader = new BufferedReader (new InputStreamReader (
                        entity.getContent (), StandardCharsets.UTF_8))) {
                    Stream < String> sm = reader.lines ();
                    sm.forEach (System.out :: println);
                }
            }
        } Catch (Exception e) {
            e.printStackTrace ();
        }
    }
}

7. Create content entity

HttpClient provides several efficient content flowing through the HTTP connection type. Examples of these classes with POST and PUT such entity enclosing requests related to the request for the content of these entities into the upcoming issue. Most of these classes are provided by HttpClient data container, such as strings, byte arrays, and file input stream corresponding to: StringEntity, ByteArrayEntity, InputStreamEntity and FileEntity. Example:

File file = new File ( "somefile.txt");
FileEntity entity = new FileEntity (file, ContentType.create ( "text / plain", "UTF-8"));
HttpPost httppost = new HttpPost ( "http: //localhost/action.do");
httppost.setEntity (entity);
 

Note: InputStreamEntity is not repeatable, because it can only be read once from the underlying data stream. InputStreamEntity usually recommended to achieve a self-contained custom HttpEntity class.

7.1 HTML form

Many applications need to simulate the process of submitting an HTML form, for example, to log on a web application or submit input data, HttpClient provides an entity class UrlEncodedFormEntity to help complete the 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: //localhost/handler.do");
httppost.setEntity (entity);
 

This UrlEncodedFormEntity entity uses URL encoding encoding parameters and produces the following:

param1 = value1 & param2 = value2
 

7.2 HTTP chunked

HttpClient is generally recommended to select the appropriate transmission coding is based on HTTP messaging features. However, there may be a priority notification HttpEntity chunked encoding (chunk coding), () method is set to true by HttpEntity of setChunked. Please note, HttpClient use this tag just for tips. When using the HTTP protocol does not support chunked encoding, this value will be ignored, such as: HTTP / 1.0. Example:
 
StringEntity entity = new StringEntity ( "important message",
    ContentType.create ( "plain / text", Consts.UTF_8));
entity.setChunked (true); // set to chunked encoding
HttpPost httppost = new HttpPost ( "http: //localhost/acrtion.do");
httppost.setEntity (entity);
 

8. response processing

Treatment response easiest and most convenient way is to use ResponseHandler interface, which contains handleResponse (HttpResponse respnse) method. This approach allows users to not worry about the connection management. When using ResponseHandler, HttpClient will automatically release the connection and the connection back connection manager, regardless of success or failure of execution request. Example:
 
package httpclienttest;
 
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
 
public class T14 {
    public static void main (String [] args) {
        CloseableHttpClient httpclient = HttpClients.createDefault ();
        HttpGet httpget = new HttpGet ( "http: // localhost / json");
        ResponseHandler < MyJsonObject> rh = new ResponseHandler < MyJsonObject> () {
            @Override
            public JsonObject handleResponse (final HttpResponse response) throws IOException {
                StatusLine statusLine = response.getStatusLine ();
                HttpEntity entity = response.getEntity ();
                if (statusLine.getStatusCode ()> = 300) {
                    throw new HttpResponseException (statusLine.getStatusCode (),
                            statusLine.getReasonPhrase ());
                }
                if (entity == null) {
                    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 = httpclient.execute (httpget, rh);
    }
}
     
         
         
         
  More:      
 
- Linux non-root user uses less than 1024 ports (Linux)
- Implement binary search algorithm in C language (Programming)
- Linux users should be aware that should the 7 ls command unique skills (Linux)
- CentOS 6.5 opens the Xmanager Remote Desktop login (Linux)
- Set up MySQL master and slave servers under Ubuntu 14.04 (Server)
- C # / iOS / Android Universal Encryption and decryption (Programming)
- Common DDOS attacks (Linux)
- C ++ in the elimination Wunused (Programming)
- GRUB2 boot Ubuntu Manual (Linux)
- How Vim playing a mature IDE (Linux)
- Bash code injection attacks through a special environment variable (Linux)
- shell-like program (Programming)
- Getting CentOS Learning Notes (Linux)
- How to create a someone project on github (Linux)
- Android Unzip the ZIP / GZIP data (based on the InflaterInputStream implementation) (Programming)
- The difference between statement and preparedStatement of the jdbc (Database)
- CentOS install expect (Linux)
- PHP CURL get cookies simulated login (Database)
- Macro Analysis Performance: PHP Performance Analysis and Experiment (Programming)
- MongoDB study notes - polymerization (Database)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.