HttpClient基本使用

maven依赖

1
2
3
4
5
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>

返回结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.example.demo.utils;

/**
* @author CUI SHIYING
*/
public class HttpResult {
/**
* 响应的状态码
*/
private int code;

/**
* 响应的响应体
*/
private String body;

public HttpResult(int code) {
this.code = code;
}

public HttpResult(int code, String body) {
this.code = code;
this.body = body;
}

public int getCode() {
return code;
}

public void setCode(int code) {
this.code = code;
}

public String getBody() {
return body;
}

public void setBody(String body) {
this.body = body;
}
}

工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
package com.example.demo.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
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.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
* @author CUI SHIYING
*/
public class HttpClientUtil {

private static final Logger log = LoggerFactory.getLogger(HttpClientUtil.class);

private static final CloseableHttpClient HTTP_CLIENT;

private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

/**
* 请求超时时间设置(10秒)
*/
private static final int TIMEOUT = 10 * 1000;

static {
RequestConfig clientConfig = RequestConfig.custom()
.setConnectTimeout(TIMEOUT)
.setSocketTimeout(TIMEOUT)
.setConnectionRequestTimeout(TIMEOUT)
.build();

List<Header> headers = new ArrayList<>();
headers.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
HTTP_CLIENT = HttpClientBuilder.create()
.setDefaultRequestConfig(clientConfig)
.setDefaultHeaders(headers)
.build();

Runtime.getRuntime().addShutdownHook(new Thread(() -> {
if (null != HTTP_CLIENT) {
try {
HTTP_CLIENT.close();
log.info("close http client success.");
} catch (IOException e) {
log.error("close http client error.", e);
}
}
}));
}


public static HttpResult doGet(String url, Map<String, Object> map) throws Exception {

URIBuilder uriBuilder = new URIBuilder(url);

if (map != null){
for (Map.Entry<String, Object> entry : map.entrySet()){
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
}
}

HttpGet httpGet = new HttpGet(uriBuilder.build());

return execute(httpGet);
}

public static HttpResult doGet(String url) throws Exception {
return doGet(url, null);
}


public static HttpResult doPost(String url, Map<String, Object> reqMap, Map<String, String> headersMap) throws Exception {

HttpPost httpPost = new HttpPost(url);
for (Map.Entry<String, String> entry : headersMap.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}

if (reqMap != null) {

// List<NameValuePair> paramList = new ArrayList<>();
// for (String key : reqMap.keySet()) {
// paramList.add(new BasicNameValuePair(key, reqMap.get(key).toString()));
// }
// UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramList, StandardCharsets.UTF_8.name());

StringEntity formEntity = new StringEntity(OBJECT_MAPPER.writeValueAsString(reqMap), StandardCharsets.UTF_8.name());

httpPost.setEntity(formEntity);
}

return execute(httpPost);
}

public static HttpResult doPostJson(String url, String json) throws IOException {

HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
return execute(httpPost);
}

public static HttpResult doPost(String url) throws Exception {
return doPost(url, null, null);
}

public static HttpResult doPut(String url, Map<String, Object> map) throws Exception {

HttpPut httpPut = new HttpPut(url);

if (map != null) {
List<NameValuePair> params = new ArrayList<>();

for (Map.Entry<String, Object> entry : map.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}

UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8.name());

httpPut.setEntity(formEntity);
}

return execute(httpPut);
}

public static HttpResult doDelete(String url, Map<String, Object> map) throws Exception {

URIBuilder uriBuilder = new URIBuilder(url);

if (map != null) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
}
}

HttpDelete httpDelete = new HttpDelete(uriBuilder.build());

return execute(httpDelete);
}

private static HttpResult execute(HttpRequestBase httpRequest) throws IOException {
CloseableHttpResponse response = null;
try {
response = HTTP_CLIENT.execute(httpRequest);
if (Objects.nonNull(response) && Objects.nonNull(response.getStatusLine())) {
String content = "";
if (Objects.nonNull(response.getEntity())) {
content = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8.name());
}
return new HttpResult(response.getStatusLine().getStatusCode(), content);
}
return new HttpResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
} finally {
release(response);
}
}

public static void release(CloseableHttpResponse httpResponse) throws IOException {
// 释放资源
if (httpResponse != null) {
httpResponse.close();
}
}
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.example.demo.controller;

import com.example.demo.utils.HttpClientUtil;
import com.example.demo.utils.HttpResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
* @author cuishiying
* @date 2021-01-22
*/
@RestController
@RequestMapping
public class HttpTest {

private static final Logger log = LoggerFactory.getLogger(HttpTest.class);
// 请求总数
public static int clientTotal = 3000;
// 同时并发执行的线程数
public static int threadTotal = 200;
// 初始计数
public static int count = 0;

/**
* http://localhost:8081/http
*/
@GetMapping("/http")
public Object testHttp() throws Exception{
long start = System.currentTimeMillis();
// 线程池
ExecutorService executorService = Executors.newCachedThreadPool();
// 控制并发
final Semaphore semaphore = new Semaphore(threadTotal);
// 闭锁(让主线程等待子线程5000个任务执行完毕)
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
for (int i = 0; i < clientTotal ; i++) {
executorService.execute(() -> {
try {
// 此处能够同时获取200个令牌, 然后等待令牌释放
semaphore.acquire();
request();
// 令牌释放后其他任务才能继续执行, 直到5000任务执行完毕
semaphore.release();
} catch (Exception e) {
log.error("exception", e);
}
// 计数器-1
countDownLatch.countDown();
});
}
// 阻塞主线程, 等待子线程执行完毕(countDownLatch计数器变为0)
countDownLatch.await();
executorService.shutdown();
log.info("count:{}", count);
return System.currentTimeMillis()-start;
}

private void request() {
try {
HttpResult httpResult = HttpClientUtil.doGet("http://localhost:8081/hello");
System.out.println(httpResult.getBody());
count++;
} catch (Exception e) {
e.printStackTrace();
}
}
}

最后

本文到此结束,感谢阅读。如果您觉得不错,请关注公众号【当我遇上你】,您的支持是我写作的最大动力。

参考