Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

1. HTTPClient

1.1 introduction

HttpClient is a subproject of Apache Jakarta Common that provides an efficient, up-to-date, feature-rich client programming toolkit that supports the latest versions and recommendations of the HTTP protocol.

The website address

1.2 features

Httpclient has the following features:

  1. Standards-based, pure Java language. Http1.0 and Http1.1 are implemented
  2. All Http methods (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE) are implemented in an extensible object-oriented structure.
  3. HTTPS is supported.
  4. Establish transparent connections through Http proxies.
  5. Use the CONNECT method to establish an HTTPS connection to the tunnel through the Http proxy.
  6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos authentication scheme.
  7. Plug-in – based custom authentication scheme.
  8. Portable and reliable socket factories make it easier to use third party solutions.
  9. The connection manager supports multi-threaded applications. You can set the maximum number of connections, set the maximum number of connections for each host, and discover and close expired connections.
  10. Automatically handles cookies in set-cookies.
  11. Plug-in custom Cookie policies.
  12. The output stream of the Request avoids buffering the contents of the stream directly to the socket server.
  13. The input stream of Response can effectively read the corresponding content directly from the socket server.
  14. KeepAlive is used to maintain persistent connections in HTTP1.0 and HTTP1.1.
  15. Directly obtain the Response code and headers sent by the server.
  16. Ability to set connection timeout.
  17. Experimental support for http1.1 response caching.
  18. Source code is available free of charge under the Apache License.

1.3 Importing Dependencies

When developing a Java project, using HttpClient introduces relevant dependency information:

<! -- HttpClient dependencies -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.12</version>
</dependency>
Copy the code

1.4 Usage Process

The HttpClient process is as follows:

  1. Create an HttpClent object,
  2. Create an HttpGet or HttpPost object based on the request URL and request type,
  3. If you need to request parameters, add parameter information to the object,
  4. Call HttpClient’s execute method to send the HTTP request and receive the returned result using an HttPResponse object.
  5. HttpResponse processing of the returned result, get the required data.

2 GET request

2.1 Procedure

  1. createHttpClientObject: useHttpClients.createDefault()
  2. createHttpGetObject:
    • If it is a GET request with no arguments, the constructor is used directlyHttpGet(String url)createHttpGetObject can;
    • If it is a GET request, it can be used firstURIBuilder(String url)Create an object and call itaddParameter(String param, String value)Or,setParameter(String param, String value)To set the request parameters and call the build() method to build a URI object. Let’s use the constructorHttpGet(URI uri)To create an HttpGet object.
  3. createHttpResponseObject: To get the content of the server’s response
    • callHttpClientThe object’sexecute(HttpUriRequest request)Sends the request, and the method returns oneHttpResponse.
    • callHttpResponsetheGetAllHeaders (), getHeaders (String name)And other methods can obtain the server response header;
    • callHttpResponsethegetEntity()Method can be obtainedHttpEntityObject that wraps the server’sResponse content.
    • By calling theHttpResponsethegetStatusLine()/getStatusCode()Method to get the response status code.
  4. Release the connection.

2.2 GET Request without Parameters

An HttpGet request from an HttpClient has no parameters by default. You only need to follow the standard procedure to create and complete the request.

// get an HttpClient object
CloseableHttpClient httpclient = HttpClients.createDefault();
2. Generate a GET request
HttpGet httpget = new HttpGet("http://www.baidu.com/");
//3. Execute the GET request and return the result
CloseableHttpResponse response = httpclient.execute(httpget);
try {
    //4. Process the result response body
    HttpEntity entity = response.getEntity();
} finally {
    response.close();
}
Copy the code

2.3 GET Request with Parameters

When a GET request passes a parameter, that is, the final parameter is concatenated to the URL in the form of key=value, the HttpClient generates a URI object for the parameter, and then uses the generated URI to create an HttpGet object.

// get an HttpClient object
CloseableHttpClient httpclient = HttpClients.createDefault();
//2. Generate a URI object with parameters
URI uri = new URIBuilder(String url)
    .addParameter("key"."value")
    .buiild();
// create a get request object
HttpGet httpget = new HttpGet(uri);
//4. Execute the GET request and return the result
CloseableHttpResponse response = httpclient.execute(httpget);
try {
    //5. Process the result response body
    HttpEntity entity = response.getEntity();
} finally {
    response.close();
}
Copy the code

3. A POST request

3.1 Specific Steps

  1. createHttpClientObject: useHttpClients.createDefault();
  2. createHttpPostObject:
    • If it is a GET request with no arguments, the constructor is used directlyHttpPost(String url)createHttpPostObject can;
    • If it is a POST request with parameters, build an HttpEntity object and set the request parameters, and then call setEntity(HttpEntity Entity) to create an HttpPost object.
  3. createHttpResponseObject: This object is used by the program to get the content of the server’s response
    • callHttpClientThe object’sexecute(HttpUriRequest request)Sends the request, and the method returns oneHttpResponse.
    • callHttpResponsetheGetAllHeaders (), getHeaders (String name)And other methods can obtain the server response header;
    • callHttpResponsethegetEntity()Method to get an HttpEntity object that wraps the server’sResponse content.
    • By calling thegetStatusLine().getStatusCode()The response status code can be obtained.
  4. Release the connection.

3.2 POST Request without Parameters

A POST request without parameters can be executed directly on the created POST request

// get an HttpClient object
CloseableHttpClient httpclient = HttpClients.createDefault();
//2. Generate a POST request
HttpPost httpPost = new HttpPost("http://www.baidu.com/");
//3. Execute the GET request and return the result
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
    //4. Process the result response body
    HttpEntity entity = response.getEntity();
} finally {
    response.close();
}
Copy the code

3.3 POST Request with Parameters

A POST request passes its parameters into the request body, similar to a form submission that puts all its parameters into a form object and passes the form object into the request body.

// get an HttpClient object
CloseableHttpClient httpclient = HttpClients.createDefault();
//2. Generate a POST request
HttpPost httpPost = new HttpPost("http://www.baidu.com/");
//3. Request parameters are added to the request body, and the form is submitted
List<NameValuePair> nvpList = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair(key, val));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvps, charset);
httpPost.setEntity(formEntity);
//4. Execute the GET request and return the result
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
    //5. Process the result response body
    HttpEntity entity = response.getEntity();
} finally {
    response.close();
}
Copy the code