0. Reference articles
Detailed usage example of HttpClient
The article written by the author is very good, and all links are written in great detail. On the basis of this article, I have fine tuned the code structure to make it easier to understand, and will post the complete toolkit code at the end of the article.
1. General
1.1.httpClient overview
HTTP protocol is probably the most widely used and important protocol on the Internet. More and more Java applications need to access network resources directly through HTTP protocol. Although the basic function of accessing HTTP protocol has been provided in the java net package of JDK, for most applications, the functions provided by JDK library itself are not rich and flexible enough. HttpClient is a sub project under Apache Jakarta Common, which is used to provide an efficient, up-to-date and feature rich client programming toolkit supporting HTTP protocol, and it supports the latest versions and suggestions of HTTP protocol.
HTTP is a bit like a browser, but it's not a browser. Many people think that since HttpClient is an HTTP client programming tool, many people understand it as a browser, but in fact, HttpClient is not a browser, it is an HTTP communication library, so it only provides a subset of the functions expected by a general browser application. The most fundamental difference is that there is no user interface in HttpClient, The browser needs a rendering engine to display the page and interpret user input. For example, when the mouse clicks somewhere on the display page, there is a layout engine to calculate how to display HTML pages, including cascading style sheets and images. The javascript interpreter runs javascript code embedded in or referenced from an HTML page. Events from the user interface are passed to the javascript interpreter for processing. In addition, there are interfaces for plug-ins that can handle applets, embedded media objects (such as pdf files, Quicktime movies and Flash animation) or ActiveX controls (can perform any operation). HttpClient can only be used to transmit and receive HTTP messages programmatically through its API.
HttpClient is like a client for sending requests. After defining httpClient, the programmer will customize the configuration requested, then call httpClient.execute() to execute the request's sending and receive the response, and then close httpClient to release the resources.
1.2. General process of httpclient
- Create httpClient (http client)
- Processing parameters (param parameter is converted to string spliced on url, and body parameter is converted to json)
- Create a request and configure it according to various parameters (GET, POST)
- Declare response model response
- Send the request, assign the response to the response model, convert it into json format and return it
- Close httpClient and response to release resources
1.3 Maven dependency
Introducing httpClient dependency
<!-- httpClient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.6</version> </dependency>
Introduce fastjason dependency (process response)
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.3</version> </dependency>
2. Use examples
Create the HttpClientUtil class and declare the private static variable requestConfig.
This variable is used to further configure the request.
Define the method beforeInit() and add the annotation @ PostConstruct to it.
This method is used to initialize the variable requestConfig declared above, and the @ PostConstruct annotation will cause this method to be executed when the server is loaded.
beforeInit() code is as follows:
@PostConstruct public void beforeInit() { // configuration information HttpClientUtil.requestConfig = RequestConfig.custom() // Set connection timeout in milliseconds .setConnectTimeout(5000) // Set request timeout in milliseconds .setConnectionRequestTimeout(5000) // socket read / write timeout (unit: ms) .setSocketTimeout(5000) // Sets whether redirection is allowed (the default is true) .setRedirectsEnabled(true).build(); }
2.1. GET request without parameters
/** * 01. No parameter GET request * * @param url * @return */ public static String get(String url) throws IOException { //1. Obtain Http client CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //2. Create GET request HttpGet httpGet = new HttpGet(url); httpGet.setConfig(requestConfig); //3. Claim response model CloseableHttpResponse response = null; //4. Send request try { //4-1. The client executes (sends) the Get request response = httpClient.execute(httpGet); //4-2. Get response entity from response model HttpEntity responseEntity = response.getEntity(); //4-3. Parse the response entity into JSON in UTF-8 encoding and return it return EntityUtils.toString(responseEntity, "utf-8"); } catch (Exception e) { throw e; } finally { try { // Release resources if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }
2.2. GET request with parameters: param parameter
param parameter refers to splicing parameters onto url, like this:
(the above is the interface of postMan, which is just for demonstration)
/** * 02. GET request with parameters * * @param url * @param paramMap * @return * @throws IOException */ public static String getWithParams(String url, Map<String, Object> paramMap) throws IOException { //1. Obtain Http client CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //2. Processing parameters StringBuilder sb = new StringBuilder(); int paramCount = 0; if(paramMap != null){ paramCount = paramMap.size(); } // Loop splicing when there is at least one parameter if (paramCount != 0) { // Splice "?" first sb.append("?"); // Traverse Key and value int pointer = 0; for (Map.Entry<String, Object> entry : paramMap.entrySet()) { String key = entry.getKey(); String value = (String) entry.getValue(); //Splice data sb.append(key).append("=").append(value); if (pointer != paramCount - 1) { sb.append("&"); pointer++; } } } //3. Create GET request HttpGet httpGet = new HttpGet(url + sb.toString()); httpGet.setConfig(requestConfig); //4. Claim response model CloseableHttpResponse response = null; //5. Send request try { //5-1. The client executes (sends) the Get request response = httpClient.execute(httpGet); //5-2. Get response entity from response model HttpEntity responseEntity = response.getEntity(); //5-3. Parse the response entity into JSON in UTF-8 encoding and return it return EntityUtils.toString(responseEntity, "utf-8"); } catch (Exception e) { throw e; } finally { try { // Release resources if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }
2.3. No parameter POST request
The nonparametric POST request is almost the same as the nonparametric GET request. You only need to replace HttpGet with HttpPost
/** * 03. No parameter POST request * * @param url * @return */ public static String post(String url) throws IOException { //1. Obtain Http client CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //2. Create POST request HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig); //3. Claim response model CloseableHttpResponse response = null; //4. Send request try { //4-1. The client executes (sends) the Get request response = httpClient.execute(httpPost); //4-2. Get response entity from response model HttpEntity responseEntity = response.getEntity(); //4-3. Parse the response entity into JSON in UTF-8 encoding and return it return EntityUtils.toString(responseEntity, "utf-8"); } catch (Exception e) { throw e; } finally { try { // Release resources if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }
2.4. POST request with parameters: param parameter
The method of adding param parameters to the POST request is the same as that of the GET request. Both parameters are spliced on the url.
/** * 04. Parameter POST request in params * * @param url * @param paramMap * @return * @throws IOException */ public static String postWithParams(String url, Map<String, Object> paramMap) throws IOException { //1. Obtain Http client CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //2. Processing parameters StringBuilder sb = new StringBuilder(); int paramCount = 0; if(paramMap != null){ paramCount = paramMap.size(); } // Loop splicing when there is at least one parameter if (paramCount != 0) { // Splice "?" first sb.append("?"); // Traverse Key and value int pointer = 0; for (Map.Entry<String, Object> entry : paramMap.entrySet()) { String key = entry.getKey(); String value = (String) entry.getValue(); //Splice data sb.append(key).append("=").append(value); if (pointer != paramCount - 1) { sb.append("&"); pointer++; } } } //3. Create POST request HttpPost httpPost = new HttpPost(url + sb.toString()); httpPost.setConfig(requestConfig); //4. Claim response model CloseableHttpResponse response = null; //5. Send request try { //5-1. The client executes (sends) the POST request response = httpClient.execute(httpPost); //5-2. Get response entity from response model HttpEntity responseEntity = response.getEntity(); //5-3. Parse the response entity into JSON in UTF-8 encoding and return it return EntityUtils.toString(responseEntity, "utf-8"); } catch (Exception e) { throw e; } finally { try { // Release resources if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }
2.5. POST request with parameters: body parameter
The body parameter generally means that the parameters are placed in form data.
At this point, the parameters are no longer spliced to the url. When the formal parameter of the interface is the object type, the json of the object needs to be encapsulated in form data when sending the request.
Note: you need to change the content type of the request header to application/json;charset=utf8
/** * 05. Parameter POST request in body * * @param url * @return */ public static String postWithBody(String url, Object body) throws IOException { //1. Obtain Http client CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //2. Processing request parameters StringEntity stringEntity = null; if (body != null) { //2-1. Convert value to JSON String jsonValue = JSON.toJSONString(body); //2-2. Convert JSON value into stringEntity in UTF-8 encoding stringEntity = new StringEntity(jsonValue, "UTF-8"); } //3. Create POST request HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig); if (body != null) { //3-1. Put the parameters into the body httpPost.setEntity(stringEntity); //3-2. Set the request header to json mode httpPost.setHeader("Content-Type", "application/json;charset=utf8"); } //4. Claim response model CloseableHttpResponse response = null; //5. Send request try { //5-1. The client executes (sends) the Get request response = httpClient.execute(httpPost); //5-2. Get response entity from response model HttpEntity responseEntity = response.getEntity(); //5-3. Parse the response entity into JSON in UTF-8 encoding and return it return EntityUtils.toString(responseEntity, "utf-8"); } catch (Exception e) { throw e; } finally { try { // Release resources if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }
2.6. POST request with parameters: param parameter + body parameter
In essence, it is the sum of the above two participating POST requests.
Splice the param parameter onto the url, put the body parameter into the form data and modify the request header.
/** * 06. Parameter POST request in param and body at the same time * * @ param url * @ param paramMap * @ param body * @ return * @ throws IOException */public static String postWithMix(String url, Map<String, Object> paramMap, Object body) throws IOException { //1. Get Http client closeablehttpclient httpclient = httpclientbuilder. Create(). Build()// 2. Process param parameter StringBuilder sb = new stringbuilder(); int paramCount = 0; If (parammap! = null) {paramcount = parammap. Size();} / / if there is at least one parameter, loop splicing if (paramcount! = 0) {/ / splice "?" sb.append("?"); / / traverse Key and value int pointer = 0; for (map. Entry < string, Object > entry: parammap. Entryset()) {string Key = entry. Getkey()) ; string value = (string) entry. Getvalue(); / / splice data sb. Append (Key). Append ("="). Append (value); if (pointer! = paramcount - 1) {sb.append("&"); pointer + +;}}} / / 3. Process the body parameter stringentity stringentity = null; If (body! = null) {/ / 3-1. Convert value value to JSON string jsonvalue = json.tojsonstring (body); / / 3-2. Convert JSON value to stringentity in UTF-8 encoding stringentity = new stringentity (jsonvalue, "UTF-8");} / / 4. Create POST request / / 4-1. Add param parameter httppost httppost = new httppost (URL + sb. Tostring()); httpPost.setConfig(requestConfig); If (body! = null) {/ / 4-2. Add the body parameter httppost.setentity (stringentity); / / 4-3. Set the request header to JSON mode httppost.setheader ("content type", "application / JSON; charset = utf8");} / / 5. Declare the response model closeablehttpresponse response = null// 6. Send request try {/ / 6-1. The client executes (sends) the get request response = httpclient.execute (httppost); / / 6-2. Get the response entity httpentity from the response model. Responseentity = response. Getentity(); / / 6-3. Parse the response entity into JSON in UTF-8 encoding and return entityutilities.tostring (responseentity, "UTF-8");} catch (exception E) {throw E;} finally {try {/ / release resources if (httpclient! = null) {httpclient. Close();} if (response! = null) {response. Close();}} catch (IOException E) {e.printstacktrace();} }}
2.7. POST request for uploading non reference files
The MultipartEntityBuilder class is required for file upload. After the MultipartFile is built, the built MultipartEntityBuilder is assigned to httpEntity like the POST request of the body parameter. The remaining operations are exactly the same.
Note: there is no need to set additional request headers here
/** * 07. POST request for file upload without parameters * * @ param fileMap * @ return */public static String postFile(String url, Map<String, MultipartFile> fileMap) throws IOException { //1. Get the Http client closeablehttpclient httpclient = httpclientbuilder. Create(). Build(); / / 2. Process the file MultipartEntityBuilder builder = MultipartEntityBuilder. Create(); httpentity = null; / / 2-1. Traverse the key and value of the map and get all the files if (FILEMAP! = null) {for (map. Entry < string, multipartfile > entry: FILEMAP. Entryset()) {string key = entry. Getkey(); multipartfile value = entry. Getvalue(); / / 2-1. Add the file to the parameter builder. Addbinarybody ("file", value. Getinputstream(), contenttype. Application_octet_stream, key) ; / / 2-2. Build MultipartEntityBuilder and assign it to httpentity httpentity = builder. Build();}} / / 3. Create POST request httppost httppost = new httppost (URL); httppost.setconfig (requestconfig); if (FILEMAP! = null) {httppost.setentity (httpentity);} //4. Declare the response model closeablehttpresponse response = null; / / 5. Send the request try {/ / 5-1. The client executes (sends) the get request response = httpclient. Execute (httppost); / / 5-2. Obtain the response entity httpentity responseentity = response. Getentity () from the response model ; / / 5-3. Parse the response entity into JSON in UTF-8 encoding and return return entityutils.tostring (responseentity, "UTF-8");} catch (exception E) {throw E;} finally {try {/ / release the resource if (httpclient! = null) {httpclient. Close();} if (response! = null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } }}
2.8. POST request for uploading files with parameters: param parameter
In fact, it is the sum of the param parameter POST request (2.4) and the nonparametric file upload POST request (2.7).
The param parameter is spliced onto the url, and the file is built with multipart filebuilder and assigned to httpEntity.
/** * 08. Parameter POST request for file upload in param * * @ param fileMap * @ return */public static String postFileWithParams(String url, Map<String, Object> paramMap, Map<String, MultipartFile> fileMap) throws IOException { //1. Obtain Http client closeablehttpclient. Httpclient = httpclientbuilder. Create(). Build()// 2. Process param parameter StringBuilder sb = new stringbuilder(); int paramCount = 0; If (parammap! = null) {paramcount = parammap. Size();} / / if there is at least one parameter, loop splicing if (paramcount! = 0) {/ / splice "?" sb.append("?"); / / traverse key and value int pointer = 0; for (map. Entry < string, Object > entry: parammap. Entryset()) {string key = entry. Getkey()) ; string value = (string) entry. Getvalue(); / / splice data sb. Append (key). Append ("="). Append (value); if (pointer! = paramcount - 1) {sb.append("&"); pointer + +;}}} / / 3. Process file MultipartEntityBuilder builder builder = MultipartEntityBuilder. Create() ; HttpEntity httpEntity = null; // 3-1. Traverse the key and value of the map and get all the files if (FILEMAP! = null) {for (map. Entry < string, multipartfile > entry: FILEMAP. Entryset()) {string key = entry. Getkey(); multipartfile value = entry. Getvalue(); / / 2-1. Add the file to the parameter builder. Addbinarybody ("file", value. Getinputstream (), contenttype. Application_octet_stream, key); / / 2-2. Build MultipartEntityBuilder and assign it to httpentity httpentity = builder. Build();}} / / 4. Create POST request / / 4-1. Add param parameters httppost httppost = new httppost (URL + sb. Tostring()); httppost.setconfig (requestconfig) ; / / 4-2. Add the file parameter if (FILEMAP! = null) {httppost.setentity (httpentity);} / / 5. Declare the response model closeablehttpresponse response = null; / / 6. Send the request try {/ / 6-1. The client executes (sends) the get request response = httpclient.execute (httppost) ; / / 6-2. Get the response entity httpentity from the response model. Responseentity = response. Getentity(); / / 6-3. Parse the response entity into JSON in UTF-8 and return return entityutils.tostring (responseentity, "UTF-8");} catch (exception E) {throw E;} finally {try {/ / release the resource if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } }}
3. Code sorting: put forward the public part
According to the analysis of the above codes, in fact, many codes are reused. Therefore, the repeated parts can be extracted to facilitate the later maintenance of the codes.
3.1. Create HttpGet
HttpGet needs to be created before sending a GET request. Extract this part of the code and use it as the underlying function
/** * Underlying function: create httpGet * * @ param url * @ param paramMap * @ return */public static HttpGet baseCreateHttpGet(String url, Map<String, Object> paramMap) { //1. Set param parameter StringBuilder sb = new stringbuilder(); int paramcount = 0; if (parammap! = null) {paramcount = parammap. Size();} / / when there is at least one parameter, loop splicing if (paramcount! = 0) {/ / splice "?" sb.append("?"); / / traverse Key and value int pointer = 0; for (map. Entry < string, Object > entry: parammap. Entryset()) {string Key = entry. Getkey(); string value = (string) entry. Getvalue(); / / splice data sb. Append (Key). Append ("="). Append (value); if (pointer! = paramcount - 1) {sb.append("&"); pointer + +;} }} / / 2. Create GET request httpget httpget = new httpget (URL + sb); httpget.setconfig (requestconfig); return httpget;}
3.2. Create HttpPost
Before sending a POST request, you need to create an HttpPost. Extract this part of the code and use it as the underlying function.
/** * Underlying function: create httpPost * * @ param url * @ param paramMap * @ param body * @ return */private static HttpPost baseCreateHttpPost(String url, Map<String, Object> paramMap, Object body) { //1. Process param parameter StringBuilder sb = new stringbuilder(); int paramcount = 0; if (parammap! = null) {paramcount = parammap. Size();} / / when there is at least one parameter, loop splicing if (paramcount! = 0) {/ / splice "?" sb.append("?"); / / traverse Key and value int pointer = 0; for (map. Entry < string, Object > entry: parammap. Entryset()) {string Key = entry. Getkey(); string value = (string) entry. Getvalue(); / / splice data sb. Append (Key). Append ("="). Append (value); if (pointer! = paramcount - 1) {sb.append("&"); pointer + +;} }} / / 2. Process the body parameter stringentity stringentity = null; if (body! = null) {/ / 3-1. Convert the value value to JSON string jsonvalue = json.tojsonstring (body); / / 3-2. Convert the JSON value to stringentity stringentity = new stringentity (jsonvalue, "UTF-8") in UTF-8 encoding;} //3. Create POST request / / 3-1. Add param parameter httppost httppost = new httppost (URL + sb. Tostring()); httppost.setconfig (requestconfig); if (body! = null) {/ / 3-2. Add body parameter httppost.setentity (stringentity); / / 3-3. Set the request header to JSON mode httppost.setheader ("content type", "application/json;charset=utf8"); } return httpPost;}
3.3. Create HttpPost with file
To send a POST request with a file, you need to convert the file into a StringEntity and assign it to httpEntity. Based on this, this part of the code is extracted separately as the underlying function call.
/** * Underlying function: create httpPost request with file * * @ param url * @ param paramMap * @ param fileMap * @ return * @ throws IOException */private static HttpPost baseCreateHttpPostWithFile(String url, Map<String, Object> paramMap, Map<String, MultipartFile> fileMap) throws IOException { //1. Process param parameter StringBuilder sb = new stringbuilder(); int paramCount = 0; If (parammap! = null) {paramcount = parammap. Size();} / / if there is at least one parameter, loop splicing if (paramcount! = 0) {/ / splice "?" sb.append("?"); / / traverse key and value int pointer = 0; for (map. Entry < string, Object > entry: parammap. Entryset()) {string key = entry. Getkey()) ; string value = (string) entry. Getvalue(); / / splice data sb. Append (key). Append ("="). Append (value); if (pointer! = paramcount - 1) {sb.append("&"); pointer + +;}}} / / 2. Process file MultipartEntityBuilder builder builder = MultipartEntityBuilder. Create() ; HttpEntity httpEntity = null; // 2-1. Traverse the key and value of the map and get all the files if (FILEMAP! = null) {for (map. Entry < string, multipartfile > entry: FILEMAP. Entryset()) {string key = entry. Getkey(); multipartfile value = entry. Getvalue(); / / 2-1. Add the file to the parameter builder. Addbinarybody ("file", value. Getinputstream (), contenttype. Application_octet_stream, key); / / 2-2. Build MultipartEntityBuilder and assign it to httpentity httpentity = builder. Build();}} / / 3. Create POST request / / 3-1. Add param parameters httppost httppost = new httppost (URL + sb. Tostring()); httppost.setconfig (requestconfig) ; / / 3-2. Add the file parameter if (FILEMAP! = null) {httppost.setentity (httpentity);} return httppost;}
3.4. Create HttpClient and send request
In fact, the only difference between the above methods is that their HttpGet or HttpPost are different. Therefore, this part of the code is extracted, while HttpGet and HttpPost are extracted as method parameters.
HttpGet and HttpPost inherit the HttpRequestBase class, so the formal parameter type of the method is determined as the HttpRequestBase class.
/** * Underlying function: send request * * @ param httpRequestBase * @ return * @ throws IOException */private static String baseSendRequest(HttpRequestBase httpRequestBase) throws IOException { //1. Get Http client closeablehttpclient httpclient = httpclientbuilder. Create(). Build(); / / 2. Declare response model closeablehttpresponse response = null; / / 3. Send request try {/ / 3-1. Execute (send) request by client response = httpclient.execute (httprequestbase) ; / / 3-2. Get the response entity httpentity from the response model. Responseentity = response. Getentity(); / / 3-3. Parse the response entity into JSON in UTF-8 and return return entityutils.tostring (responseentity, "UTF-8");} catch (exception E) {throw E;} finally {try {/ / release the resource if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } }}
3.5. Remaining codes
The remaining code is to create different requests according to different methods and parameters, and create httpClient, send requests and obtain responses. After the public parts are extracted, the code becomes very concise.
/** * 01. No parameter GET request * * @ param url * @ return */public static String get(String url) throws IOException { //1. Create httpget httpget GET = basecreatehttpget (URL, null); / / 2. Send the request and return the response result return baseSendRequest(get);}/** * 02. GET request with parameters * * @ param url * @ param paramMap * @ return * @ throws IOException */ Public static string getwithparams (string URL, map < string, Object > parammap) throws IOException {/ / 1. Create httpget httpget GET = basecreatehttpget (URL, parammap); / / 2. Send the request and return the response result return baseSendRequest(get);}/** * 03. POST request without participation * * @ param url * @ return */ Public static string POST (string URL) throws IOException {/ / 1. Create httppost httppost POST = basecreatehttppost (URL, null, null); / / 2. Send the request and return the response result return baseSendRequest(post);}/** * 04. POST request with parameters in params * * @ param url * @ param paramMap * @ return * @ throws IOException */ Public static string postwithparams (string URL, map < string, Object > parammap) throws IOException {/ / 1. Create httppost httppost POST = basecreatehttppost (URL, parammap, null); / / 2. Send the request and return the response result return baseSendRequest(post);}/** * 05. POST request of parameter in body * * @ param url * @ return */ Public static string postwithbody (string URL, object body) throws IOException {/ / 1. Create httppost httppost POST = basecreatehttppost (URL, null, body); / / 2. Send the request and return the response result return baseSendRequest(post);}/** * 06. POST request with parameters in param and body at the same time * * @ param url * @ param paramMap * @ param body * @ return * @ throws IOException */ Public static string postwithmix (string URL, map < string, Object > parammap, object body) throws IOException {/ / 1. Create httppost httppost POST = basecreatehttppost (URL, parammap, body); / / 2. Send the request and return the response result return baseSendRequest(post);}/** * 07. POST request for file upload without parameters * * @ param fileMap * @ return */ Public static string postfile (string URL, map < string, multipartfile > FILEMAP) throws IOException {/ / 1. Create httppost httppost with file POST = basecreatehttppostwithfile (URL, null, FILEMAP); / / 2. Send the request and return the response result return baseSendRequest(post);}/** * 08. Parameter upload POST request in param file * * @ param fileMap * @ return */ Public static string postfilewithparams (string URL, map < string, Object > parammap, map < string, multipartfile > FILEMAP) throws IOException {/ / 1. Create httppost httppost with file POST = basecreatehttppostwithfile (URL, parammap, FILEMAP); / / 2. Send the request and return the response result return baseSendRequest(post);}}
4. Complete code
4.1. Before sorting
package com.eshang.http.client.learning.util; import com.alibaba.fastjson.JSON; import org.apache.http.HttpEntity; import org.apache.http.client.config.RequestConfig; 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.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.springframework.web.multipart.MultipartFile; import javax.annotation.PostConstruct; import java.io.IOException; import java.util.Map; /** * @author xyx-Eshang */ public class HttpClientUtil { private static RequestConfig requestConfig; @PostConstruct public void beforeInit() { // configuration information HttpClientUtil.requestConfig = RequestConfig.custom() // Set connection timeout in milliseconds .setConnectTimeout(5000) // Set request timeout in milliseconds .setConnectionRequestTimeout(5000) // socket read / write timeout (unit: ms) .setSocketTimeout(5000) // Sets whether redirection is allowed (the default is true) .setRedirectsEnabled(true).build(); } /** * 01. No parameter GET request * * @param url * @return */ public static String get(String url) throws IOException { //1. Obtain Http client CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //2. Create GET request HttpGet httpGet = new HttpGet(url); httpGet.setConfig(requestConfig); //3. Claim response model CloseableHttpResponse response = null; //4. Send request try { //4-1. The client executes (sends) the Get request response = httpClient.execute(httpGet); //4-2. Get response entity from response model HttpEntity responseEntity = response.getEntity(); //4-3. Parse the response entity into JSON in UTF-8 encoding and return it return EntityUtils.toString(responseEntity, "utf-8"); } catch (Exception e) { throw e; } finally { try { // Release resources if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 02. GET request with parameters * * @param url * @param paramMap * @return * @throws IOException */ public static String getWithParams(String url, Map<String, Object> paramMap) throws IOException { //1. Obtain Http client CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //2. Processing parameters StringBuilder sb = new StringBuilder(); int paramCount = paramMap.size(); // Loop splicing when there is at least one parameter if (paramCount != 0) { // Splice "?" first sb.append("?"); // Traverse Key and value int pointer = 0; for (Map.Entry<String, Object> entry : paramMap.entrySet()) { String key = entry.getKey(); String value = (String) entry.getValue(); //Splice data sb.append(key).append("=").append(value); if (pointer != paramCount - 1) { sb.append("&"); pointer++; } } } //3. Create GET request HttpGet httpGet = new HttpGet(url + sb.toString()); httpGet.setConfig(requestConfig); //4. Claim response model CloseableHttpResponse response = null; //5. Send request try { //5-1. The client executes (sends) the Get request response = httpClient.execute(httpGet); //5-2. Get response entity from response model HttpEntity responseEntity = response.getEntity(); //5-3. Parse the response entity into JSON in UTF-8 encoding and return it return EntityUtils.toString(responseEntity, "utf-8"); } catch (Exception e) { throw e; } finally { try { // Release resources if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 03. No parameter POST request * * @param url * @return */ public static String post(String url) throws IOException { //1. Obtain Http client CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //2. Create POST request HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig); //3. Claim response model CloseableHttpResponse response = null; //4. Send request try { //4-1. The client executes (sends) the Get request response = httpClient.execute(httpPost); //4-2. Get response entity from response model HttpEntity responseEntity = response.getEntity(); //4-3. Parse the response entity into JSON in UTF-8 encoding and return it return EntityUtils.toString(responseEntity, "utf-8"); } catch (Exception e) { throw e; } finally { try { // Release resources if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 04. Parameter POST request in params * * @param url * @param paramMap * @return * @throws IOException */ public static String postWithParams(String url, Map<String, Object> paramMap) throws IOException { //1. Obtain Http client CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //2. Processing parameters StringBuilder sb = new StringBuilder(); int paramCount = paramMap.size(); // Loop splicing when there is at least one parameter if (paramCount != 0) { // Splice "?" first sb.append("?"); // Traverse Key and value int pointer = 0; for (Map.Entry<String, Object> entry : paramMap.entrySet()) { String key = entry.getKey(); String value = (String) entry.getValue(); //Splice data sb.append(key).append("=").append(value); if (pointer != paramCount - 1) { sb.append("&"); pointer++; } } } //3. Create POST request HttpPost httpPost = new HttpPost(url + sb.toString()); httpPost.setConfig(requestConfig); //4. Claim response model CloseableHttpResponse response = null; //5. Send request try { //5-1. The client executes (sends) the POST request response = httpClient.execute(httpPost); //5-2. Get response entity from response model HttpEntity responseEntity = response.getEntity(); //5-3. Parse the response entity into JSON in UTF-8 encoding and return it return EntityUtils.toString(responseEntity, "utf-8"); } catch (Exception e) { throw e; } finally { try { // Release resources if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 05. Parameter POST request in body * * @param url * @return */ public static String postWithBody(String url, Object body) throws IOException { //1. Obtain Http client CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //2. Processing request parameters StringEntity stringEntity = null; String jsonValue; if (body != null) { //2-1. Convert value to JSON jsonValue = JSON.toJSONString(body); //2-2. Convert JSON value into stringEntity in UTF-8 encoding stringEntity = new StringEntity(jsonValue, "UTF-8"); } //3. Create POST request HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig); if (body != null) { //3-1. Put the parameters into the body httpPost.setEntity(stringEntity); //3-2. Set the request header to json mode httpPost.setHeader("Content-Type", "application/json;charset=utf8"); } //4. Claim response model CloseableHttpResponse response = null; //5. Send request try { //5-1. The client executes (sends) the Get request response = httpClient.execute(httpPost); //5-2. Get response entity from response model HttpEntity responseEntity = response.getEntity(); //5-3. Parse the response entity into JSON in UTF-8 encoding and return it return EntityUtils.toString(responseEntity, "utf-8"); } catch (Exception e) { throw e; } finally { try { // Release resources if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 06. Parameter POST request in param and body at the same time * * @param url * @param paramMap * @param body * @return * @throws IOException */ public static String postWithMix(String url, Map<String, Object> paramMap, Object body) throws IOException { //1. Get Http client CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //2. Process param parameters StringBuilder sb = new StringBuilder(); int paramCount = paramMap.size(); // Loop splicing when there is at least one parameter if (paramCount != 0) { // Splice "?" first sb.append("?"); // Traverse Key and value int pointer = 0; for (Map.Entry<String, Object> entry : paramMap.entrySet()) { String key = entry.getKey(); String value = (String) entry.getValue(); //Splice data sb.append(key).append("=").append(value); if (pointer != paramCount - 1) { sb.append("&"); pointer++; } } } //3. Handle body parameters StringEntity stringEntity = null; String jsonValue = null; if (body != null) { //3-1. Convert value to JSON jsonValue = JSON.toJSONString(body); //3-2. Convert JSON value to stringEntity in UTF-8 encoding stringEntity = new StringEntity(jsonValue, "UTF-8"); } //4. Create POST request //4-1. Add param parameter HttpPost httpPost = new HttpPost(url + sb.toString()); httpPost.setConfig(requestConfig); if (body != null) { //4-2. Add the body parameter httpPost.setEntity(stringEntity); //4-3. Set the request header to json mode httpPost.setHeader("Content-Type", "application/json;charset=utf8"); } //5. Claim response model CloseableHttpResponse response = null; //6. Send request try { //6-1. The client executes (sends) the Get request response = httpClient.execute(httpPost); //6-2. Get response entity from response model HttpEntity responseEntity = response.getEntity(); //6-3. Parse the response entity into JSON in UTF-8 encoding and return it return EntityUtils.toString(responseEntity, "utf-8"); } catch (Exception e) { throw e; } finally { try { // Release resources if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 07. POST request for file upload without parameters * * @param fileMap * @return */ public static String postFile(String url, Map<String, MultipartFile> fileMap) throws IOException { //1. Obtain Http client CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //2. Processing documents MultipartEntityBuilder builder = MultipartEntityBuilder.create(); HttpEntity httpEntity = null; //2-1. Traverse the key and value of the map to get all the files if (fileMap != null) { for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) { String key = entry.getKey(); MultipartFile value = entry.getValue(); //2-1. Add file to parameters builder.addBinaryBody("file", value.getInputStream(), ContentType.APPLICATION_OCTET_STREAM, key); //2-2. Build MultipartEntityBuilder and assign it to HttpEntity httpEntity = builder.build(); } } //3. Create POST request HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig); if (fileMap != null) { httpPost.setEntity(httpEntity); } //4. Claim response model CloseableHttpResponse response = null; //5. Send request try { //5-1. The client executes (sends) the Get request response = httpClient.execute(httpPost); //5-2. Get response entity from response model HttpEntity responseEntity = response.getEntity(); //5-3. Parse the response entity into JSON in UTF-8 encoding and return it return EntityUtils.toString(responseEntity, "utf-8"); } catch (Exception e) { throw e; } finally { try { // Release resources if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 08. Parameter POST request for file upload in param * * @param fileMap * @return */ public static String postFileWithParams(String url, Map<String, Object> paramMap, Map<String, MultipartFile> fileMap) throws IOException { //1. Obtain Http client CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //2. Process param parameters StringBuilder sb = new StringBuilder(); int paramCount = paramMap.size(); // Loop splicing when there is at least one parameter if (paramCount != 0) { // Splice "?" first sb.append("?"); // Traverse Key and value int pointer = 0; for (Map.Entry<String, Object> entry : paramMap.entrySet()) { String key = entry.getKey(); String value = (String) entry.getValue(); //Splice data sb.append(key).append("=").append(value); if (pointer != paramCount - 1) { sb.append("&"); pointer++; } } } //3. Processing documents MultipartEntityBuilder builder = MultipartEntityBuilder.create(); HttpEntity httpEntity = null; //3-1. Traverse the key and value of the map to get all the files if (fileMap != null) { for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) { String key = entry.getKey(); MultipartFile value = entry.getValue(); //2-1. Add file to parameters builder.addBinaryBody("file", value.getInputStream(), ContentType.APPLICATION_OCTET_STREAM, key); //2-2. Build MultipartEntityBuilder and assign it to HttpEntity httpEntity = builder.build(); } } //4. Create POST request //4-1. Add param parameter HttpPost httpPost = new HttpPost(url + sb.toString()); httpPost.setConfig(requestConfig); //4-2. Add file parameters if (fileMap != null) { httpPost.setEntity(httpEntity); } //5. Claim response model CloseableHttpResponse response = null; //6. Send request try { //6-1. The client executes (sends) the Get request response = httpClient.execute(httpPost); //6-2. Get response entity from response model HttpEntity responseEntity = response.getEntity(); //6-3. Parse the response entity into JSON in UTF-8 encoding and return it return EntityUtils.toString(responseEntity, "utf-8"); } catch (Exception e) { throw e; } finally { try { // Release resources if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
3.2. After finishing
package com.eshang.http.client.learning.util; import com.alibaba.fastjson.JSON; import org.apache.http.HttpEntity; import org.apache.http.client.config.RequestConfig; 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.client.methods.HttpRequestBase; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.springframework.web.multipart.MultipartFile; import javax.annotation.PostConstruct; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * @author xyx-Eshang */ public class HttpClientUtil { private static RequestConfig requestConfig; @PostConstruct public void beforeInit() { // configuration information HttpClientUtil.requestConfig = RequestConfig.custom() // Set connection timeout in milliseconds .setConnectTimeout(5000) // Set request timeout in milliseconds .setConnectionRequestTimeout(5000) // socket read / write timeout (unit: ms) .setSocketTimeout(5000) // Sets whether redirection is allowed (the default is true) .setRedirectsEnabled(true).build(); } /** * Underlying function: create httpGet * * @param url * @param paramMap * @return */ public static HttpGet baseCreateHttpGet(String url, Map<String, Object> paramMap) { //1. Set param parameter StringBuilder sb = new StringBuilder(); int paramCount = 0; if (paramMap != null) { paramCount = paramMap.size(); } // Loop splicing when there is at least one parameter if (paramCount != 0) { // Splice "?" first sb.append("?"); // Traverse Key and value int pointer = 0; for (Map.Entry<String, Object> entry : paramMap.entrySet()) { String key = entry.getKey(); String value = (String) entry.getValue(); //Splice data sb.append(key).append("=").append(value); if (pointer != paramCount - 1) { sb.append("&"); pointer++; } } } //2. Create GET request HttpGet httpGet = new HttpGet(url + sb); httpGet.setConfig(requestConfig); return httpGet; } /** * Underlying function: create httpPost * * @param url * @param paramMap * @param body * @return */ private static HttpPost baseCreateHttpPost(String url, Map<String, Object> paramMap, Object body) { //1. Process param parameters StringBuilder sb = new StringBuilder(); int paramCount = 0; if (paramMap != null) { paramCount = paramMap.size(); } // Loop splicing when there is at least one parameter if (paramCount != 0) { // Splice "?" first sb.append("?"); // Traverse Key and value int pointer = 0; for (Map.Entry<String, Object> entry : paramMap.entrySet()) { String key = entry.getKey(); String value = (String) entry.getValue(); //Splice data sb.append(key).append("=").append(value); if (pointer != paramCount - 1) { sb.append("&"); pointer++; } } } //2. Process the body parameter StringEntity stringEntity = null; if (body != null) { //3-1. Convert value to JSON String jsonValue = JSON.toJSONString(body); //3-2. Convert JSON value to stringEntity in UTF-8 encoding stringEntity = new StringEntity(jsonValue, "UTF-8"); } //3. Create POST request //3-1. Add param parameter HttpPost httpPost = new HttpPost(url + sb.toString()); httpPost.setConfig(requestConfig); if (body != null) { //3-2. Add the body parameter httpPost.setEntity(stringEntity); //3-3. Set the request header to json mode httpPost.setHeader("Content-Type", "application/json;charset=utf8"); } return httpPost; } /** * Underlying function: create httpPost request with file * * @param url * @param paramMap * @param fileMap * @return * @throws IOException */ private static HttpPost baseCreateHttpPostWithFile(String url, Map<String, Object> paramMap, Map<String, MultipartFile> fileMap) throws IOException { //1. Process param parameters StringBuilder sb = new StringBuilder(); int paramCount = 0; if (paramMap != null) { paramCount = paramMap.size(); } // Loop splicing when there is at least one parameter if (paramCount != 0) { // Splice "?" first sb.append("?"); // Traverse Key and value int pointer = 0; for (Map.Entry<String, Object> entry : paramMap.entrySet()) { String key = entry.getKey(); String value = (String) entry.getValue(); //Splice data sb.append(key).append("=").append(value); if (pointer != paramCount - 1) { sb.append("&"); pointer++; } } } //2. Processing documents MultipartEntityBuilder builder = MultipartEntityBuilder.create(); HttpEntity httpEntity = null; //2-1. Traverse the key and value of the map to get all the files if (fileMap != null) { for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) { String key = entry.getKey(); MultipartFile value = entry.getValue(); //2-1. Add file to parameters builder.addBinaryBody("file", value.getInputStream(), ContentType.APPLICATION_OCTET_STREAM, key); //2-2. Build MultipartEntityBuilder and assign it to HttpEntity httpEntity = builder.build(); } } //3. Create POST request //3-1. Add param parameter HttpPost httpPost = new HttpPost(url + sb.toString()); httpPost.setConfig(requestConfig); //3-2. Add file parameters if (fileMap != null) { httpPost.setEntity(httpEntity); } return httpPost; } /** * Underlying function: send request * * @param httpRequestBase * @return * @throws IOException */ private static String baseSendRequest(HttpRequestBase httpRequestBase) throws IOException { //1. Obtain Http client CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //2. Claim response model CloseableHttpResponse response = null; //3. Send request try { //3-1. The client executes (sends) the request response = httpClient.execute(httpRequestBase); //3-2. Get response entity from response model HttpEntity responseEntity = response.getEntity(); //3-3. Parse the response entity into JSON in UTF-8 encoding and return it return EntityUtils.toString(responseEntity, "utf-8"); } catch (Exception e) { throw e; } finally { try { // Release resources if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 01. No parameter GET request * * @param url * @return */ public static String get(String url) throws IOException { //1. Create httpGet HttpGet get = baseCreateHttpGet(url, null); //2. Send the request and return the response result return baseSendRequest(get); } /** * 02. GET request with parameters * * @param url * @param paramMap * @return * @throws IOException */ public static String getWithParams(String url, Map<String, Object> paramMap) throws IOException { //1. Create httpGet HttpGet get = baseCreateHttpGet(url, paramMap); //2. Send the request and return the response result return baseSendRequest(get); } /** * 03. No parameter POST request * * @param url * @return */ public static String post(String url) throws IOException { //1. Create httpPost HttpPost post = baseCreateHttpPost(url, null, null); //2. Send the request and return the response result return baseSendRequest(post); } /** * 04. Parameter POST request in params * * @param url * @param paramMap * @return * @throws IOException */ public static String postWithParams(String url, Map<String, Object> paramMap) throws IOException { //1. Create httpPost HttpPost post = baseCreateHttpPost(url, paramMap, null); //2. Send the request and return the response result return baseSendRequest(post); } /** * 05. Parameter POST request in body * * @param url * @return */ public static String postWithBody(String url, Object body) throws IOException { //1. Create httpPost HttpPost post = baseCreateHttpPost(url, null, body); //2. Send the request and return the response result return baseSendRequest(post); } /** * 06. Parameter POST request in param and body at the same time * * @param url * @param paramMap * @param body * @return * @throws IOException */ public static String postWithMix(String url, Map<String, Object> paramMap, Object body) throws IOException { //1. Create httpPost HttpPost post = baseCreateHttpPost(url, paramMap, body); //2. Send the request and return the response result return baseSendRequest(post); } /** * 07. POST request for file upload without parameters * * @param fileMap * @return */ public static String postFile(String url, Map<String, MultipartFile> fileMap) throws IOException { //1. Create httpPost with file HttpPost post = baseCreateHttpPostWithFile(url, null, fileMap); //2. Send the request and return the response result return baseSendRequest(post); } /** * 08. Parameter POST request for file upload in param * * @param fileMap * @return */ public static String postFileWithParams(String url, Map<String, Object> paramMap, Map<String, MultipartFile> fileMap) throws IOException { //1. Create httpPost with file HttpPost post = baseCreateHttpPostWithFile(url, paramMap, fileMap); //2. Send the request and return the response result return baseSendRequest(post); } }