创建SpringBoot项目,我的版本为2.2.6
引入依赖,如下
<!-- 必需:Spring-Web模块 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 可选:处理JSON数据相关的包 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.68</version>
</dependency>
<!-- 可选:单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
只对restful 四种请求方式进行说明
HTTP Method | RestTemplate methods |
---|---|
GET | getForObject |
getForEntity | |
POST | postForObject |
postForEntity | |
postForLocation | |
PUT | put |
DELETE | delete |
这两个方法和上述方法使用方式一致,只是多了一个参数,来指定HttpMethod。类比于SpringMVC,如 @PostMapping(value = “models”)和@RequestMapping(value = “model”, method = RequestMethod.POST)
代码实例:
String response = template.postForObject(url, requestEntity, String.class);
ResponseEntity<String> responseEntity = template.postForEntity(url, requestEntity, String.class);
xxxForObject()和execute(),我们只需要关心响应体(Response Body),Spring帮助我们将响应体数据封装成我们期望的数据类型。
xxxForEntity()和exchange(),我们关心的是整个响应(Response)。
将默认编码 ISO-8859-8 --> UTF-8
public static void encondingConvert(RestTemplate template){
List<HttpMessageConverter<?>> converters = template.getMessageConverters();
Iterator<HttpMessageConverter<?>> iterator = converters.iterator();
while(iterator.hasNext()){
HttpMessageConverter<?> converter = iterator.next();
if(converter instanceof StringHttpMessageConverter){
((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
}
}
}
@Test
public void doGet() {
RestTemplate template = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "bearer jRSTh9WCVRVuENeutdoBJw1d2sUXYO");
headers.set("Accept", "*/*");
HttpEntity request = new HttpEntity(headers);
/** 由于getForObject()和getForEntity()不能封装请求头,所以此处使用exchange() */
/** 使用restful风格,使用占位符 */
String url = "http://127.0.0.1:9999/product/images/{1}";
Integer urlVariavle = 313926502;
ResponseEntity<String> response = template.exchange(url, HttpMethod.GET, request, String.class, urlVariavle);
System.out.println(response.getBody());
}
@Test
public void doPost(){
/** 获取Spring提供的rest模板对象,构建一个Http客户端 */
RestTemplate template = new RestTemplate();
/** 解决中文乱码问题:调用 0中方法 */
encondingConvert(template);
/** 获取Header对象 */
HttpHeaders httpHeaders = new HttpHeaders();
/** 设置Content-Type:application/json */
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
/** 请求头添加其他信息,如token等 */
httpHeaders.set("Accept","*/*");
httpHeaders.set("Authorization","bearer jRSTh9WCVRVuENeutdoBJw1d2sUXYO");
/** 请求体的数据 */
Map<String, String> map = new HashMap<>();
map.put("model_desc", "这是一个描述");
map.put("region", "CLINDER");
map.put("user", "[email protected]");
/**
description: 将请求体和请求头封装成Http request
param1: 请求体,传入map或字符串;
底层会将map转成json格式数据,或直接传入json格式字符串
param2: 请求头
*/
HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(map, httpHeaders);
String url = "http://127.0.0.1:9999/product/models";
/**
description: 发送post请求
method: postForObject
param1: 服务器url
param2: 上面封装好的Http request
param3: Class类型,响应体的类型:可以String;
可以是自定义实体类,内部自动将响应体封装实体类对象;
可以是集合、数组
return: param3的Class类型
*/
// String response = template.postForObject(url, requestEntity, String.class);
/**
postForEntity()与postForObject()的区别:
return: Http response类型,对response的操作更多,可以查看完整的resopnse
*/
ResponseEntity<String> responseEntity = template.postForEntity(url, requestEntity, String.class);
System.out.println(responseEntity.getBody());
}
@Test
public void doPut() {
RestTemplate template = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.set("Authorization","bearer jRSTh9WCVRVuENeutdoBJw1d2sUXYO");
headers.set("Accept","*/*");
/** 使用FileSystemResource,获取本地的文件 */
String filePath = "C:\\Users\\zhaocy\\Desktop\\jdk api 1.8.CHM";
FileSystemResource resource = new FileSystemResource(filePath);
/** 使用接口MultiValueMap,是Map的子类 */
MultiValueMap<String, Object> map = new LinkedMultiValueMap();
/** 使用add(),非put() */
map.add("model", resource);
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map, headers);
String url = "http://127.0.0.1:9999/product/models/" + 1615058163;
/** 由于put()返回值类型:void,此处使用exchange()提交put请求 */
// template.put(url, request);
ResponseEntity<String> response = template.exchange(url, HttpMethod.PUT, request, String.class);
System.out.println(response.getBody());
}
未完待续
本文参考链接:
https://www.cnblogs.com/javazhiyin/p/9851775.html