Details on the use of HttpClient in Java projects

  • 2020-04-01 04:16:38
  • OfStack

The importance of the Http protocol believe I don't need to say more, than traditional HttpClient JDK own URLConnection, increases the ease of use and flexibility (specific distinction, we discuss it later) in the future, it is not only the client sends an Http request, but also convenient for developer testing interface (based on Http protocol), which improve the efficiency of development, is also convenient to improve the robustness of the code. Therefore, proficiency in HttpClient is a very important compulsory content, after mastering HttpClient, I believe that the understanding of Http protocol will be more in-depth.

A list,

HttpClient is a subproject under Apache Jakarta Common to provide an efficient, up-to-date, and feature-rich client-side programming toolkit that supports HTTP, and it supports the latest versions and recommendations of the HTTP protocol. HttpClient has been used in many projects, such as Cactus and HTMLUnit, two other open source projects that are well known in Apache Jakarta.

Download address: (link: http://hc.apache.org/downloads.cgi)

Second, the characteristics of

1. Standards-based, pure Java language. Http1.0 and Http1.1 are implemented
2. Implement all Http methods (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE) in an extensible object-oriented structure.
3. Support HTTPS protocol.
Establish a transparent connection through the Http proxy.
5. Use the CONNECT method to establish an HTTPS connection through the Http proxy.
6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos authentication scheme.
7. Plug-in - style custom authentication scheme.
8. The portable and reliable socket factory makes it easier to use third-party solutions.
Connection manager supports multi-threaded applications. Support for setting the maximum number of connections, as well as for setting the maximum number of connections per host to find and close expired connections.
10. Automatically handles cookies in set-cookie.
11. Plug-in custom Cookie policy.
The output stream of Request prevents the contents of the stream from being buffered directly to the socket server.
13. The input stream of Response can effectively read the corresponding content directly from the socket server.
14. Keep a persistent connection using KeepAlive in http1.0 and http1.1.
15. Directly get the response code and headers sent by the server.
16. Ability to set connection timeout.
17. Experimental support for http1.1 response caching.
18. The source code is freely available under the Apache License.

Use method

Sending a request and receiving a response using HttpClient is simple and generally requires the following steps.

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.

3. If the request parameters need to be sent, the setParams(HetpParams params) method Shared by HttpGet and HttpPost can be called to add the request parameters; For the HttpPost object, you can also call the setEntity(HttpEntity entity) method to set the request parameters.

4. Call the execute(HttpUriRequest request) of the HttpClient object to send the request, and the method returns an HttpResponse.

5. Call HttpResponse's getAllHeaders(), getHeaders(String name) and other methods to get the response headers of the server; The getEntity() method of calling HttpResponse gets the HttpEntity object that wraps the response content of the server. This object is used by the program to get the response content of the server.

Release the connection. Regardless of the success of the execution method, the connection must be released

Four, the instance,


package com.test; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.io.UnsupportedEncodingException; 
import java.security.KeyManagementException; 
import java.security.KeyStore; 
import java.security.KeyStoreException; 
import java.security.NoSuchAlgorithmException; 
import java.security.cert.CertificateException; 
import java.util.ArrayList; 
import java.util.List; 
import javax.net.ssl.SSLContext; 
import org.apache.http.HttpEntity; 
import org.apache.http.NameValuePair; 
import org.apache.http.ParseException; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.CloseableHttpResponse; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.conn.ssl.SSLConnectionSocketFactory; 
import org.apache.http.conn.ssl.SSLContexts; 
import org.apache.http.conn.ssl.TrustSelfSignedStrategy; 
import org.apache.http.entity.ContentType; 
import org.apache.http.entity.mime.MultipartEntityBuilder; 
import org.apache.http.entity.mime.content.FileBody; 
import org.apache.http.entity.mime.content.StringBody; 
import org.apache.http.impl.client.CloseableHttpClient; 
import org.apache.http.impl.client.HttpClients; 
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.util.EntityUtils; 
import org.junit.Test; 
public class HttpClientTest { 
  @Test 
  public void jUnitTest() { 
    get(); 
  } 
   
  public void ssl() { 
    CloseableHttpClient httpclient = null; 
    try { 
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
      FileInputStream instream = new FileInputStream(new File("d:\tomcat.keystore")); 
      try { 
        //To load the keyStore d:   tomcat keyStore
        trustStore.load(instream, "123456".toCharArray()); 
      } catch (CertificateException e) { 
        e.printStackTrace(); 
      } finally { 
        try { 
          instream.close(); 
        } catch (Exception ignore) { 
        } 
      } 
      //Trust your own 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 HTTP request (get mode)
      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(); 
        } 
      } 
    } 
  } 
   
  public void postForm() { 
    //Create the default instance of httpClient.
    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 and free the resource
      try { 
        httpclient.close(); 
      } catch (IOException e) { 
        e.printStackTrace(); 
      } 
    } 
  } 
   
  public void post() { 
    //Create the default instance of httpClient.
    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 and free the resource
      try { 
        httpclient.close(); 
      } catch (IOException e) { 
        e.printStackTrace(); 
      } 
    } 
  } 
   
  public void get() { 
    CloseableHttpClient httpclient = HttpClients.createDefault(); 
    try { 
      //Create 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("--------------------------------------"); 
        //Print response state
        System.out.println(response.getStatusLine()); 
        if (entity != null) { 
          //Print the response content length
          System.out.println("Response content length: " + entity.getContentLength()); 
          //Print response content
          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 and free the resource
      try { 
        httpclient.close(); 
      } catch (IOException e) { 
        e.printStackTrace(); 
      } 
    } 
  } 
   
  public void upload() { 
    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(); 
      } 
    } 
  } 
}
</namevaluepair></namevaluepair>
</namevaluepair></namevaluepair> 

This example is using the latest version of HttpClient4.3. This version and the previous code writing style is quite different, you pay more attention.


Related articles: