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:
- Standards-based, pure Java language. Http1.0 and Http1.1 are implemented
- All Http methods (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE) are implemented in an extensible object-oriented structure.
- HTTPS is supported.
- Establish transparent connections through Http proxies.
- Use the CONNECT method to establish an HTTPS connection to the tunnel through the Http proxy.
- Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos authentication scheme.
- Plug-in – based custom authentication scheme.
- Portable and reliable socket factories make it easier to use third party solutions.
- 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.
- Automatically handles cookies in set-cookies.
- Plug-in custom Cookie policies.
- The output stream of the Request avoids buffering the contents of the stream directly to the socket server.
- The input stream of Response can effectively read the corresponding content directly from the socket server.
- KeepAlive is used to maintain persistent connections in HTTP1.0 and HTTP1.1.
- Directly obtain the Response code and headers sent by the server.
- Ability to set connection timeout.
- Experimental support for http1.1 response caching.
- 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:
- Create an HttpClent object,
- Create an HttpGet or HttpPost object based on the request URL and request type,
- If you need to request parameters, add parameter information to the object,
- Call HttpClient’s execute method to send the HTTP request and receive the returned result using an HttPResponse object.
- HttpResponse processing of the returned result, get the required data.
2 GET request
2.1 Procedure
- create
HttpClient
Object: useHttpClients.createDefault()
- create
HttpGet
Object:- If it is a GET request with no arguments, the constructor is used directly
HttpGet(String url)
createHttpGet
Object can; - If it is a GET request, it can be used first
URIBuilder(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.
- If it is a GET request with no arguments, the constructor is used directly
- create
HttpResponse
Object: To get the content of the server’s response- call
HttpClient
The object’sexecute(HttpUriRequest request)
Sends the request, and the method returns oneHttpResponse
. - call
HttpResponse
theGetAllHeaders (), getHeaders (String name)
And other methods can obtain the server response header; - call
HttpResponse
thegetEntity()
Method can be obtainedHttpEntity
Object that wraps the server’sResponse content. - By calling the
HttpResponse
thegetStatusLine()/getStatusCode()
Method to get the response status code.
- call
- 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
- create
HttpClient
Object: useHttpClients.createDefault()
; - create
HttpPost
Object:- If it is a GET request with no arguments, the constructor is used directly
HttpPost(String url)
createHttpPost
Object 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.
- If it is a GET request with no arguments, the constructor is used directly
- create
HttpResponse
Object: This object is used by the program to get the content of the server’s response- call
HttpClient
The object’sexecute(HttpUriRequest request)
Sends the request, and the method returns oneHttpResponse
. - call
HttpResponse
theGetAllHeaders (), getHeaders (String name)
And other methods can obtain the server response header; - call
HttpResponse
thegetEntity()
Method to get an HttpEntity object that wraps the server’sResponse content. - By calling the
getStatusLine().getStatusCode()
The response status code can be obtained.
- call
- 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