HttpClient is a client-side HTTP communication implementation library. The goal of HttpClient is to send and receive HTTP messages.
I believe I don’t need to say more about the importance of the Http protocol. Compared with the URLConnection that comes with the traditional JDK, HttpClient has increased ease of use and flexibility (we will discuss the specific differences in the future). It is not only a way for the client to send Http requests. It is easy, and it also facilitates developers to test the interface (based on the HTTP protocol), which not only improves the efficiency of development, but also facilitates the improvement of the robustness of the code. Therefore, proficiency in HttpClient is very important and compulsory. After mastering HttpClient, I believe that the understanding of the Http protocol will be deeper.
1. Introduction
HttpClient is a sub-project under Apache Jakarta Common, used to provide an efficient, up-to-date, feature-rich client programming toolkit that supports the HTTP protocol, and it supports the latest version and recommendations of the HTTP protocol. HttpClient has been used in many projects. For example, two other famous open source projects on Apache Jakarta, Cactus and HTMLUnit, both use HttpClient.
Download address: http://hc.apache.org/downloads.cgi
2. Characteristics
1. Based on standard and pure java language. Implemented Http1.0 and Http1.1
2. Implements all Http methods (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE) with an extensible object-oriented structure.
3. Support HTTPS protocol.
4. Establish a transparent connection through HTTP proxy.
5. Use the CONNECT method to establish a tunneled https connection through the Http proxy.
6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos authentication scheme.
7. Plug-in custom authentication scheme.
8. Portable and reliable socket factory makes it easier to use third-party solutions.
9. The connection manager supports multi-threaded applications. Supports setting the maximum number of connections, as well as setting the maximum number of connections for each host, and discovers and closes expired connections.
10. Automatically handle cookies in Set-Cookie.
11. Plug-in custom cookie policy.
12. The output stream of Request can avoid buffering the content in 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. Use KeepAlive 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. The source code is freely available under the Apache License.
3. How to use
It is very simple to use HttpClient to send requests and receive responses. Generally, the following steps are required.
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 you need to send request parameters, you can call the setParams (HetpParams params) method common to HttpGet and HttpPost to add request parameters; for the HttpPost object, you can also call the setEntity (HttpEntity entity) method to set the request parameters.
4. Call execute(HttpUriRequest request) of the HttpClient object to send the request. This method returns an HttpResponse.
5. Call HttpResponse's getAllHeaders(), getHeaders(String name) and other methods to obtain the server's response headers; call HttpResponse's getEntity() method to obtain the HttpEntity object, which wraps the server's response content. The program can obtain the server's response content through this object.
6. Release the connection. Regardless of whether the execution method is successful or not, the connection must be released
4. Examples
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(); } /** * HttpClient connects to SSL */ public void ssl() { 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 own CA and all self-signed certificates SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build() ; // Only allow the use of TLSv1 protocol 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(); } } } } /** * Submit the form in post mode (simulate user login request) */ public void postForm() { // Create a default httpClient instance. CloseableHttpClient httpclient = HttpClients.createDefault(); // Create httppost HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action"); // Create 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 release resources try { httpclient .close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Send a post request to access the local application and return different results according to different parameters passed */ public void post() { // Create a default httpClient instance. CloseableHttpClient httpclient = HttpClients.createDefault(); // Create an httppost HttpPost httppost = new HttpPost(" http://localhost:8080/myDemo/Ajax/serivceJ.action"); // Create 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 release resources try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Send a get request*/ 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 get request. CloseableHttpResponse response = httpclient.execute(httpget); try { // Get the response entity HttpEntity entity = response.getEntity(); System.out.println("-------------------------- ----------"); // Print response status System.out.println(response.getStatusLine()); if (entity != null) { // Print response content length System.out.println("Response content length: " + entity.getContentLength()); //Print the 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 release resources try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Upload files*/ 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 uses the latest version of HttpClient4.3. This version is quite different from the previous code writing style, so please pay more attention.
Okay, the above is the entire content of this article, I hope you like it.