SpringBoot 整合 HttpClient,后端调用远程接口

SpringBoot 整合 HttpClient

添加 HttpClient 依赖

SpringBoot 项目中的 pom.xml 文件中添加 HttpClient 的起步依赖:

1
2
3
4
5
<!-- HttpClient 起步依赖 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>

HttpClient 发送 GET 请求

先尝试通过 HttpClient 发送 GET 请求:

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
@RestController
public class HttpClientController {

@GetMapping("/testGet")
public String httpClientTestGet() throws IOException {
String result = "";
// 要请求的远程连接(此为我本地另开的一个服务,即:http://localhost:8082/queryUser)
String url = "http://172.20.10.2:8082/queryUser";

// 创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建GET方式请求对象
HttpGet httpGet = new HttpGet(url);

// 设置请求头信息
// httpGet.setHeader("Cookie", "JSESSIONID=xxxxxxx");

// 执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = httpClient.execute(httpGet);

// 获取结果实体
// 判断网络连接状态码是否正常(0--200都数正常)
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity(), "utf-8");
}
// 释放链接
response.close();

return result;
}
}

通过访问:http://localhost:8080/testGet 测试该远程 GET 请求是否成功。

HttpClient 发送 POST 请求

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
@GetMapping("/testPost")
public String httpClientTestPost() throws IOException {
String result = "";
// json数据:{"username": "testPost","password": "1234","realname": "post 测试"}
String json="{\"username\": \"testPost\",\"password\": \"1234\",\"realname\": \"post 测试\"}";
// 若传入的是个对象,可使用 fastjson 工具包将其转为json字符串

// 要请求的远程连接
String url = "http://172.20.10.2:8088/addUser";

// 创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();

// 创建post方式请求对象
HttpPost httpPost = new HttpPost(url);

// 设置参数到请求对象中,这里内容类型设为json
StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
stringEntity.setContentEncoding("utf-8");
httpPost.setEntity(stringEntity);

// 执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = httpClient.execute(httpPost);

// 获取结果实体
// 判断网络连接状态码是否正常(0--200都属正常)
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity(), "utf-8");
}
System.out.println(response.getStatusLine().getStatusCode());
// 释放链接
response.close();

return result;
}

通过访问:http://localhost:8080/testGet 测试该远程 POST 请求是否成功。

查询数据库,添加成功。

PUTDELETE 同理可以这样进行请求,不一一赘述。

下面将这常用的四个请求方法整合为一个工具类,以使得大部分的请求都能直接调用工具类中的方法实现。

整合 HttpClient 请求方法

编写 CommonMethod.java 工具类,该类为静态类,可直接通过类名调用里面的方法。

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
package com.rk.utils;

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.*;
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.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class CommonMethod {

// GET 请求
public static String commonGet(String url) throws IOException {
String result = "";

CloseableHttpClient httpClient = HttpClients.createDefault();

HttpGet httpGet = new HttpGet(url);

CloseableHttpResponse response = httpClient.execute(httpGet);

if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity(), "utf-8");
}

return result;
}

// POST 请求
public static String commonPost(String url, String json) throws IOException {
String result = "";

CloseableHttpClient httpClient = HttpClients.createDefault();

HttpPost httpPost = new HttpPost(url);

StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
stringEntity.setContentEncoding("utf-8");

httpPost.setEntity(stringEntity);

CloseableHttpResponse response = httpClient.execute(httpPost);

if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity(), "utf-8");
}

return result;
}

// PUT 请求
public static String commonPut(String url, String json) throws IOException {
String result = "";

CloseableHttpClient httpClient = HttpClients.createDefault();

HttpPut httpPut = new HttpPut(url);

StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
stringEntity.setContentEncoding("utf-8");

httpPut.setEntity(stringEntity);

CloseableHttpResponse response = httpClient.execute(httpPut);

if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity(), "utf-8");
}

return result;
}

// DELETE 请求
public static String commonDelete(String url) throws IOException {
String result = "";

CloseableHttpClient httpClient = HttpClients.createDefault();

HttpDelete httpDelete = new HttpDelete(url);

CloseableHttpResponse response = httpClient.execute(httpDelete);

if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity(), "utf-8");
}

return result;
}

}

该工具类的调用:

1
2
3
4
5
6
7
8
// 调用 GET
CommonMethod.commonGet(url);
// 调用 POST
CommonMethod.commonPost(url, json);
// 调用 PUT
CommonMethod.commonPut(url, json);
// 调用 DELETE
CommonMethod.commonDelete(url);

常用的请求是 GETPOTSPUTDELETE 这四个请求方法。其中 GETDELETE 一般只需要传入请求路径 url 就可完成调用,简单的 POSTPUT 方法也只需传入 urlbody 数据就可调用成功。

这是学习工作中整理的,有参考网上别人的教程。只是简单的远程调用接口,复杂的可以设置请求头参数,POST 的时候传入 Map 或者 form 表单数据等。这些我暂时用不到,暂不深究。