1、概述
HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新版本。
使用步骤一般如下:
- 创建HttpClient对象
- 创建请求方法的实例
- 调用HttpClient对象的execute发送请求并获得响应对象HttpResponse
- 释放连接
2、pom.xml
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>${javax.ws-version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
</dependencies>
2、get请求
public String doGet(String url, Map<String, String> paramMap) {
// 创建Http客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建httpGet
HttpGet httpGet = new HttpGet();
// 响应对象
CloseableHttpResponse response = null;
String entityResult = "";
try {
// 配置信息
RequestConfig requestConfig = RequestConfig.custom()
// 设置连接超时时间(单位毫秒)
.setConnectTimeout(5000)
// 设置请求超时时间(单位毫秒)
.setConnectionRequestTimeout(5000)
// socket读写超时时间(单位毫秒)
.setSocketTimeout(5000)
// 设置是否允许重定向(默认为true)
.setRedirectsEnabled(true).build();
httpGet.setConfig(requestConfig);
URIBuilder uriBuilder = new URIBuilder(url);
paramMap.forEach(uriBuilder::addParameter);
URI uri = uriBuilder.build();
httpGet.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
httpGet.setURI(uri);
// 发送请求获得响应
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
entityResult = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
//关闭响应
if (null != response) {
response.close();
}
//关闭客户端
if (null != httpClient) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return entityResult;
}
3、post请求
public String doPost(String url, Map<String, String> basicParamMap, Object objectParam) {
// 创建Http客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建httpPost
HttpPost httpPost = new HttpPost();
// 响应对象
CloseableHttpResponse response = null;
String entityResult = "";
try {
// 配置信息
RequestConfig requestConfig = RequestConfig.custom()
// 设置连接超时时间(单位毫秒)
.setConnectTimeout(5000)
// 设置请求超时时间(单位毫秒)
.setConnectionRequestTimeout(5000)
// socket读写超时时间(单位毫秒)
.setSocketTimeout(5000)
// 设置是否允许重定向(默认为true)
.setRedirectsEnabled(true).build();
httpPost.setConfig(requestConfig);
URIBuilder uriBuilder = new URIBuilder(url);
// 普通参数:将参数放入键值对类NameValuePair中,再放入集合中
List<NameValuePair> params = new ArrayList<>();
basicParamMap.forEach((key, value) -> params.add(new BasicNameValuePair(key, value)));
uriBuilder.setParameters(params);
// 将对象转换为json字符串,并放入entity中
StringEntity entity = new StringEntity(JSON.toJSONString(objectParam), StandardCharsets.UTF_8);
httpPost.setEntity(entity);
URI uri = uriBuilder.build();
httpPost.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
httpPost.setURI(uri);
// 发送请求获得响应
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
entityResult = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
//关闭响应
if (null != response) {
response.close();
}
//关闭客户端
if (null != httpClient) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return entityResult;
}