Detailed usage example of httpclient

Strange soft [email protected] 2022-01-26 18:35:04 阅读数:61

detailed usage example httpclient

1、 Import dependence

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>

2、 Use tool class

The tool class will get Request and post Several parameter transfer methods in the request are written , Among them is get Address bar reference 、get Of params The ginseng 、post Of params The ginseng 、post Of json The ginseng .

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpClientUtil {

private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
private static final int DEFULT_TIMEOUT = 30 * 1000;// Default timeout 20 second 
/** * You can visit http://localhost:9005/yzhwsj/addPersonal/1/2 Such an interface * @param url * @param headers * @param urlParam * @param timeout * @return */
private static String doUrlGet(String url, Map<String, String> headers, List<String> urlParam, Integer timeout) {

// establish httpClient object 
CloseableHttpClient httpClient = HttpClients.createDefault();
String resultString = null;
CloseableHttpResponse response = null;
try {

// establish uri
if (urlParam != null){

for (String param : urlParam) {

url = url + "/" + param;
}
}
// establish hTTP get request 
HttpGet httpGet = new HttpGet(url);
// Set timeout 
int timeoutTmp = DEFULT_TIMEOUT;
if (timeout != null) {

timeoutTmp = timeout;
}
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
.setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
httpGet.setConfig(requestConfig);
// Set header information 
if (null != headers) {

for (String key : headers.keySet()) {

httpGet.setHeader(key, headers.get(key));
}
}
// Perform the requested 
response = httpClient.execute(httpGet);
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {

resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
}
} catch (IOException e) {

logger.error("http Call exception " + e.toString(), e);
} finally {

try {

if (null != response) {

response.close();
}
} catch (IOException e) {

logger.error("response Close exception " + e.toString(), e);
}
try {

if (null != httpClient) {

httpClient.close();
}
} catch (IOException e) {

logger.error("httpClient Close exception " + e.toString(), e);
}
}
return resultString;
}
/** * @param url * @param headers * @param params * @param timeout * @return */
private static String doGet(String url, Map<String, String> headers, Map<String, Object> params, Integer timeout) {

// establish httpClient object 
CloseableHttpClient httpClient = HttpClients.createDefault();
String resultString = null;
CloseableHttpResponse response = null;
try {

// 1. establish uri
URIBuilder builder = new URIBuilder(url);
if (params != null) {

//uri Add parameter 
for (String key : params.keySet()) {

builder.addParameter(key, String.valueOf(params.get(key)));
}
}
URI uri = builder.build();
// 2. establish hTTP get request 
HttpGet httpGet = new HttpGet(uri);
// 3. Set timeout 
int timeoutTmp = DEFULT_TIMEOUT;
if (timeout != null) {

timeoutTmp = timeout;
}
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
.setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
httpGet.setConfig(requestConfig);
// 4. Set header information 
if (null != headers) {

for (String key : headers.keySet()) {

httpGet.setHeader(key, headers.get(key));
}
}
// 5. Perform the requested 
response = httpClient.execute(httpGet);
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {

resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
}
} catch (URISyntaxException e) {

logger.error("http Call exception " + e.toString(), e);
} catch (IOException e) {

logger.error("http Call exception " + e.toString(), e);
} finally {

try {

if (null != response) {

response.close();
}
} catch (IOException e) {

logger.error("response Close exception " + e.toString(), e);
}
try {

if (null != httpClient) {

httpClient.close();
}
} catch (IOException e) {

logger.error("httpClient Close exception " + e.toString(), e);
}
}
return resultString;
}
/** * call http post request (json data ) * * @param url * @param headers * @param json * @return */
public static String doJsonPost(String url, Map<String, String> headers, JSONObject json, Integer timeout) {

CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {

// 1. establish http post request 
HttpPost httpPost = new HttpPost(url);
// 2. Set timeout 
int timeoutTmp = DEFULT_TIMEOUT;
if (timeout != null) {

timeoutTmp = timeout;
}
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
.setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
httpPost.setConfig(requestConfig);
// 3. Set parameter information 
StringEntity s = new StringEntity(json.toString(), Consts.UTF_8);
// send out json The data needs to be set contentType
s.setContentType("application/json");
httpPost.setEntity(s);
// 4. Set header information 
if (headers != null) {

for (String key : headers.keySet()) {

httpPost.setHeader(key, headers.get(key));
}
}
// 5. perform http request 
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
}
} catch (UnsupportedEncodingException e) {

logger.error(" call http abnormal " + e.toString(), e);
} catch (ClientProtocolException e) {

logger.error(" call http abnormal " + e.toString(), e);
} catch (IOException e) {

logger.error(" call http abnormal " + e.toString(), e);
} finally {

try {

if (null != response) {

response.close();
}
} catch (IOException e) {

logger.error(" close response abnormal " + e.toString(), e);
}
try {

if (null != httpClient) {

httpClient.close();
}
} catch (IOException e) {

logger.error(" close httpClient abnormal " + e.toString(), e);
}
}
return resultString;
}
/** * call http post request Basic method * * @param url Requested url * @param headers Request header * @param params Parameters * @param timeout Timeout time * @return */
public static String doPost(String url, Map<String, String> headers, Map<String, Object> params, Integer timeout) {

CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {

// 1. establish http post request 
HttpPost httpPost = new HttpPost(url);
// 2. Set timeout 
int timeoutTmp = DEFULT_TIMEOUT;
if (timeout != null) {

timeoutTmp = timeout;
}
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
.setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
httpPost.setConfig(requestConfig);
// 3. Set parameter information 
if (params != null) {

List<NameValuePair> paramList = new ArrayList<>();
for (String key : params.keySet()) {

paramList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
}
// Simulation form 
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, Consts.UTF_8);
httpPost.setEntity(entity);
}
// 4. Set header information 
if (headers != null) {

for (String key : headers.keySet()) {

httpPost.setHeader(key, headers.get(key));
}
}
// 5. perform http request 
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
}
} catch (UnsupportedEncodingException e) {

logger.error(" call http abnormal " + e.toString(), e);
} catch (ClientProtocolException e) {

logger.error(" call http abnormal " + e.toString(), e);
} catch (IOException e) {

logger.error(" call http abnormal " + e.toString(), e);
} finally {

try {

if (null != response) {

response.close();
}
} catch (IOException e) {

logger.error(" close response abnormal " + e.toString(), e);
}
try {

if (null != httpClient) {

httpClient.close();
}
} catch (IOException e) {

logger.error(" close httpClient abnormal " + e.toString(), e);
}
}
return resultString;
}
}

3、 Expand

The above tool class , All the methods are carried token And overtime , If the interface is not used, you can expand the interface . for example :

/** * call http get request * * @param url * @param params * @return */
public static String doGet(String url, Map<String, Object> params) {

return doGet(url, null, params, null);
}

If it involves put Request and delete request , Similar to the above , It's just that when you create a request, it's changed to :

HttpDelete httpDelete = new HttpDelete();
HttpPut httpPut = new HttpPut();
copyright:author[Strange soft [email protected]],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/01/202201261835018591.html