I don’t need to tell you more about the importance of Http. HttpClient provides more ease of use and flexibility than URLConnection in the JDK. Moreover, it is also convenient for developers to test the interface (based on Http protocol), which improves the efficiency of development and the robustness of the code. Therefore, it is very important to master HttpClient. After mastering HttpClient, I believe that the understanding of Http protocol will be more in-depth.
A list,
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. HttpClient has been used in many projects, such as Cactus and HTMLUnit, two other well-known open source projects on Apache Jakarta that use HttpClient.
Download address: hc.apache.org/downloads.c…
Second, the characteristics of
-
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.
Three, use method
Using HttpClient to send a request and receive a response is simple.
1. Create an HttpClient object.
2. Create an instance of the request method and specify the request URL. If you need to send a GET request, create an HttpGet object; If you need to send a POST request, create an HttpPost object.
HetpParams params (HetpParams params) HttpGet (HetpParams params); For HttpPost objects, you can also call setEntity(HttpEntity Entity) to set request parameters.
4. Call the HttpClient object’s execute(HttpUriRequest Request) to send the request. This method returns an HttpResponse.
5. Call methods such as HttpResponse getAllHeaders() and getHeaders(String name) to obtain the response headers of the server. Call HttpResponse’s getEntity() method to obtain the HttpEntity object, which wraps the server’s response content. The program can use this object to get the content of the server’s response.
6. Release the connection. Whether the execution method succeeds or not, the connection must be released.
Four, the instance,
` ` `public class HttpClientTest {
@Test
public void jUnitTest(a) {
get();
}
/** * HttpClient connection SSL */
public void ssl(a) {
CloseableHttpClient httpclient = null;
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));
try {
// Load keyStore d:\\tomcat.keystore
trustStore.load(instream, "123456".toCharArray());
} catch (CertificateException e) {
e.printStackTrace();
} finally {
try {
instream.close();
} catch (Exception ignore) {
}
}
// Trust your CA and all self-signed certificates
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
// Only the TLSv1 protocol is allowed
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
// Create an HTTP request (get)
HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");
System.out.println("executing request" + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
System.out.println(response.getStatusLine());
if(entity ! =null) {
System.out.println("Response content length: "+ entity.getContentLength()); System.out.println(EntityUtils.toString(entity)); EntityUtils.consume(entity); }}finally{ response.close(); }}catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} finally {
if(httpclient ! =null) {
try {
httpclient.close();
} catch(IOException e) { e.printStackTrace(); }}}}/** * Submit the form in post mode (simulate user login request) */
public void postForm(a) {
// Create a default httpClient instance.
CloseableHttpClient httpclient = HttpClients.createDefault();
/ / create the httppost
HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
// Create a parameter queue
List<namevaluepair> formparams = new ArrayList<namevaluepair>();
formparams.add(new BasicNameValuePair("username"."admin"));
formparams.add(new BasicNameValuePair("password"."123456"));
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if(entity ! =null) {
System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --"); }}finally{ response.close(); }}catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// Close the connection to release resources
try {
httpclient.close();
} catch(IOException e) { e.printStackTrace(); }}}/** * Sends a POST request to access the local application and returns different results according to the parameters passed */
public void post(a) {
// Create a default httpClient instance.
CloseableHttpClient httpclient = HttpClients.createDefault();
/ / create the httppost
HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
// Create a parameter queue
List<namevaluepair> formparams = new ArrayList<namevaluepair>();
formparams.add(new BasicNameValuePair("type"."house"));
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if(entity ! =null) {
System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --"); }}finally{ response.close(); }}catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// Close the connection to release resources
try {
httpclient.close();
} catch(IOException e) { e.printStackTrace(); }}}/** * Send a get request */
public void get(a) {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
/ / to create an httpget.
HttpGet httpget = new HttpGet("http://www.baidu.com/");
System.out.println("executing request " + httpget.getURI());
// Execute the GET request.
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// Get the response entity
HttpEntity entity = response.getEntity();
System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
// Prints the response status
System.out.println(response.getStatusLine());
if(entity ! =null) {
// Prints the length of the response
System.out.println("Response content length: " + entity.getContentLength());
// Prints the response
System.out.println("Response content: " + EntityUtils.toString(entity));
}
System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -");
} finally{ response.close(); }}catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// Close the connection to release resources
try {
httpclient.close();
} catch(IOException e) { e.printStackTrace(); }}}/** * Upload file */
public void upload(a) {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");
FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if(resEntity ! =null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally{ response.close(); }}catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch(IOException e) { e.printStackTrace(); }}}}Copy the code