概述

RestTemplate 是Spring 用于同步client端的核心类,简化了与http服务的通信,并满足RestFul原则,程序代码可以给它提供URL,并提取结果

默认情况下,RestTemplate默认依赖jdk的HTTP连接工具。当然你也可以 通过setRequestFactory属性切换到不同的HTTP源,比如Apache HttpComponents、Netty或OkHttp

参考

https://zhuanlan.zhihu.com/p/31681913

img

配置

pom.xml

RestUtil.java 工具类中使用

1
2
3
4
5
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.9</version>
</dependency>

spring.xml

1
2
<!--扫描 RestTemplateConfig 所在的包-->
<context:component-scan base-package="com.bjtcrj.scm.common.utils" />

RestTemplateConfig.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
package com.bjtcrj.scm.common.utils;

import org.springframework.context.annotation.Bean;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
* 优雅的http请求方式RestTemplate
* @Return:
*/
@Component
public class RestTemplateConfig {

@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}

@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(5000);//ms
factory.setConnectTimeout(15000);//ms
return factory;
}
}

RestUtil.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
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
package com.bjtcrj.scm.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
* 调用 Restful 接口 Util
*
*/
@Slf4j
public class RestUtil {

/**
* RestAPI 调用器
*/
private final static RestTemplate RT;

static {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(3000);
requestFactory.setReadTimeout(3000);
RT = new RestTemplate(requestFactory);
// 解决乱码问题
RT.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
}

public static RestTemplate getRestTemplate() {
return RT;
}

/**
* 发送 get 请求
*/
public static JSONObject get(String url) {
return get(url, null, null);
}

/**
* 发送 get 请求
*/
public static JSONObject get(String url, JSONObject variables) {
return get(url, variables, null);
}

/**
* 发送 get 请求
*/
public static JSONObject get(String url, JSONObject variables, JSONObject params) {
return getOrDelete(url, HttpMethod.GET, variables, params, JSONObject.class).getBody();
}

/**
* 发送 delete 请求
*/
public static JSONObject delete(String url) {
return delete(url, null, null);
}

/**
* 发送 delete 请求
* @param url
* @param variables url 参数
* @return
*/
public static JSONObject delete(String url, JSONObject variables) {
return delete(url, variables, null);
}

/**
* 发送 delete 请求
* @param url
* @param variables url 参数
* @param params 请求体 参数
* @return
*/
public static JSONObject delete(String url, JSONObject variables, JSONObject params) {
return getOrDelete(url, HttpMethod.DELETE, variables, params, JSONObject.class).getBody();
}

/**
* 发送 POST 请求,返回原生 ResponseEntity 对象
*/
public static JSONObject post(String url, String contentType, JSONObject params) {
return post(url, contentType, null, params, null);
}
/**
* 发送 POST 请求,返回原生 ResponseEntity 对象
*/
public static JSONObject post(String url, String contentType, JSONObject variables, JSONObject params) {
return post(url, contentType, variables, params, null);
}
/**
* 发送 POST 请求,返回原生 ResponseEntity 对象
*/
public static JSONObject post(String url, String contentType, JSONObject params, List<File> files) {
return postOrPut(url, HttpMethod.POST, contentType, null, params, files, JSONObject.class).getBody();
}
/**
* 发送 POST 请求,返回原生 ResponseEntity 对象
*/
public static JSONObject post(String url, String contentType, JSONObject variables, JSONObject params, List<File> files) {
return postOrPut(url, HttpMethod.POST, contentType, variables, params, files, JSONObject.class).getBody();
}

/**
* 发送 put 请求
*/
public static JSONObject put(String url, JSONObject params) {
return put(url, null, params, null);
}

/**
* 发送 put 请求
*/
public static JSONObject put(String url, JSONObject variables, JSONObject params) {
return put(url, variables, params, null);
}

/**
* 发送 put 请求,返回原生 ResponseEntity 对象
*/
public static JSONObject put(String url, JSONObject params, List<File> files) {
return postOrPut(url, HttpMethod.PUT, null, null, params, files, JSONObject.class).getBody();
}
/**
* 发送 put 请求,返回原生 ResponseEntity 对象
*/
public static JSONObject put(String url, JSONObject variables, JSONObject params, List<File> files) {
return postOrPut(url, HttpMethod.PUT, null, variables, params, files, JSONObject.class).getBody();
}

/**
* 发送请求
*
* @param url 请求地址
* @param contentType contentType 可空
* @param variables 请求url参数 可空
* @param params 请求body参数 可空
* @param responseType 返回类型
* @return ResponseEntity<responseType>
*/
public static <T> ResponseEntity<T> postOrPut(String url, HttpMethod httpMethod, String contentType, JSONObject variables, JSONObject params, List<File> files, Class<T> responseType) {
log.info(" RestUtil --- request --- url = "+ url);
if (StringUtils.isEmpty(url)) {
throw new RuntimeException("url 不能为空");
}

HttpHeaders headers = new HttpHeaders();
if(contentType != null) {
headers.add("Content-Type", contentType);
}

// 拼接 url 参数
if (variables != null) {
url += ("?" + asUrlVariables(variables));
}

// 请求体
HttpEntity entity = new HttpEntity("", headers);
if (params != null) {
switch (contentType) {
case MediaType.APPLICATION_FORM_URLENCODED_VALUE:
{
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
for (Map.Entry<String, Object> e : params.entrySet()) {
body.add(e.getKey(), e.getValue());
}
entity = new HttpEntity<>(body, headers);
break;
}
case MediaType.MULTIPART_FORM_DATA_VALUE:
{
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
for (Map.Entry<String, Object> e : params.entrySet()) {
body.add(e.getKey(), e.getValue());
}

if(files != null && files.size() > 0) {
for (File file : files) {
body.add("files", new FileSystemResource(file));
}
// body.add("type", "image/jpeg");
entity = new HttpEntity<>(body, headers);
}
break;
}
case MediaType.APPLICATION_JSON_VALUE:
{
String body = params.toJSONString();
entity = new HttpEntity<>(body, headers);
break;
}
}
}

return RT.exchange(url, httpMethod, entity, responseType);
}

public static <T> ResponseEntity<T> getOrDelete(String url, HttpMethod httpMethod, JSONObject variables, Object params, Class<T> responseType) {
log.info(" RestUtil --- getOrDelete --- url = "+ url);
if (StringUtils.isEmpty(url)) {
throw new RuntimeException("url 不能为空");
}

// 拼接 url 参数
if (variables != null) {
url += ("?" + asUrlVariables(variables));
}

// 请求体
String body = "";
if (params != null) {
if (params instanceof JSONObject) {
body = ((JSONObject) params).toJSONString();
} else {
body = params.toString();
}
}

HttpHeaders headers = new HttpHeaders();
HttpEntity entity = new HttpEntity(body, headers);
return RT.exchange(url, httpMethod, entity, responseType);
}

/**
* 将 JSONObject 转为 a=1&b=2&c=3...&n=n 的形式
*/
private static String asUrlVariables(JSONObject variables) {
Map<String, Object> source = (Map) JSON.parse(variables.toJSONString());
Iterator<String> it = source.keySet().iterator();
StringBuilder urlVariables = new StringBuilder();
while (it.hasNext()) {
String key = it.next();
String value = "";
Object object = source.get(key);
if (object != null) {
if (!StringUtils.isEmpty(object.toString())) {
value = object.toString();
}
}
urlVariables.append("&").append(key).append("=").append(value);
}
// 去掉第一个&
return urlVariables.substring(1);
}

}

接口及测试示例

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
package com.bjtcrj.scm.core.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bjtcrj.scm.common.utils.Constants;
import com.bjtcrj.scm.common.utils.RestUtil;
import com.bjtcrj.scm.common.utils.StringEx;
import com.bjtcrj.scm.core.persistence.pojo.SysDict;
import com.bjtcrj.scm.core.persistence.pojo.Sysmodule;
import lombok.Data;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController {
@RequestMapping("json")
@ResponseBody
public JSONObject json(HttpServletRequest request) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "张三");
jsonObject.put("age", 20);
return jsonObject;
}

@RequestMapping("map")
@ResponseBody
public Map<String, Object> map(HttpServletRequest request) {
Map<String, Object> m = new HashMap<>();
m.put("name", "张三");
m.put("age", 20);

Sysmodule u = new Sysmodule();
u.setModulename("系统管理");
m.put("module", u);

List<SysDict> l = new ArrayList<>();
SysDict sysDict = new SysDict();
sysDict.setDictname("小区类型");
l.add(sysDict);
m.put("dict", l);
return m;
}

@RequestMapping("restGet")
@ResponseBody
public T restGet(HttpServletRequest request) {
//JSONObject jsonObject = RestUtil.get("http://localhost:8080/scm-web/json.do");
JSONObject jsonObject = RestUtil.get("http://localhost:8080/scm-web/map.do");
T t = JSON.parseObject(jsonObject.toJSONString(), T.class);
return t;
}

@RequestMapping("/postFormUrlEncoded_Client")
@ResponseBody
public JSONObject postFormUrlEncoded_Client() {
JSONObject p = new JSONObject();
p.put("name", "张三");
p.put("age", 20);

return RestUtil.post("http://localhost:8080/scm-web/postFormUrlEncoded_Server.do", MediaType.APPLICATION_FORM_URLENCODED_VALUE, p);
}

@RequestMapping(value = "postFormUrlEncoded_Server", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
@ResponseBody
public T postFormUrlEncoded_Server(T t) {
return t;
}

@RequestMapping(value = "postFormData_Server", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseBody
public T postFormData_Server(T t, HttpServletRequest request) {
System.out.println(t.toString());

MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
List<MultipartFile> files = multipartRequest.getFiles("files");
for (MultipartFile file : files) {
System.out.println(file.getOriginalFilename());
}
return t;
}

@RequestMapping("/postFormData_Client")
@ResponseBody
public JSONObject postFormData_Client() {
JSONObject p = new JSONObject();
p.put("name", "张三");
p.put("age", 20);

List<File> files = new ArrayList<>();
files.add(new File("/Users/wangwz/Pictures/leaf-1657146__480.jpg"));
files.add(new File("/Users/wangwz/Pictures/nature-3340709__480.jpg"));

return RestUtil.post("http://localhost:8080/scm-web/postFormData_Server.do", MediaType.MULTIPART_FORM_DATA_VALUE, p, files);
}

@RequestMapping("/postJSON_Client")
@ResponseBody
public JSONObject postJSON_Client() {
JSONObject p = new JSONObject();
p.put("name", "张三");
p.put("age", 20);

return RestUtil.post("http://localhost:8080/scm-web/postJSON_Server.do", MediaType.APPLICATION_JSON_VALUE, p);
}

@RequestMapping(value = "postJSON_Server", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public T postJSON_Server(@RequestBody T t) {
return t;
}

@RequestMapping("/restDelete")
@ResponseBody
public JSONObject restDelete() {
return RestUtil.delete("http://localhost:8080/scm-web/delete.do?name=张三");
}

@RequestMapping(value = "delete", method = RequestMethod.DELETE)
@ResponseBody
public JSONObject delete(@RequestParam("name") String name) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", name);
return jsonObject;
}
}

@Data
class T {
private String name;
private Integer age;
private Sysmodule module;
private List<SysDict> dict;

@Override
public String toString() {
return "T{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

http 脚本测试

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

###
GET http://localhost:8080/scm-web/json.do
###
GET http://localhost:8080/scm-web/map.do
###
GET http://localhost:8080/scm-web/restGet.do

###
DELETE http://localhost:8080/scm-web/delete.do?name=李四
###
GET http://localhost:8080/scm-web/restDelete.do

###
POST http://localhost:8080/scm-web/postFormUrlEncoded_Server.do
Content-Type: application/x-www-form-urlencoded

name=张三&age=20

###
POST http://localhost:8080/scm-web/postJSON_Server.do
Content-Type: application/json

{
"name": "张三",
"age":20
}

###
GET http://localhost:8080/scm-web/postFormUrlEncoded_Client.do

###
GET http://localhost:8080/scm-web/postJSON_Client.do

###
GET http://localhost:8080/scm-web/postFormData_Client.do