项目目录
![](https://img2020.cnblogs.com/blog/1151930/202106/1151930-20210622144052457-187263496.png)
Get请求测试类
package com.example.demo.testRestTemplate;
import com.example.demo.pojo.User;
import org.junit.Test;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
/**
* @author lyd
* @Description: Get测试
* @date 10:21
*/
public class TestGet {
RestTemplate restTemplate = new RestTemplate();
/**
* 简单无参使用
*/
@Test
public void doGetTestOne() {
String url = "http://localhost:8080/doGetTestOne";
//方式一:GET 方式获取 JSON 串数据
String result = restTemplate.getForObject(url, User.class).toString();
System.out.println("返回结果1:" + result);
//方式二:GET 方式获取 JSON 数据映射后的 User 实体对象
User user = restTemplate.getForObject(url, User.class);
System.out.println("返回结果2:" + user);
//方式三:GET 方式获取包含 User 实体对象 的响应实体 ResponseEntity 对象,用 getBody() 获取
ResponseEntity responseEntity = restTemplate.getForEntity(url, User.class);
System.out.println("返回结果3:" + responseEntity.getBody());
// 方法四
//构建请求实体 HttpEntity 对象,用于配置 Header 信息和请求参数
MultiValueMap header = new LinkedMultiValueMap();//一键多值映射
header.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
HttpEntity<Object> requestEntity = new HttpEntity<>(header);
//执行请求获取包含 Product 实体对象 的响应实体 ResponseEntity 对象,用 getBody() 获取
ResponseEntity exchangeResult = restTemplate.exchange(url, HttpMethod.GET, requestEntity, User.class);
System.out.println("状态值:" + exchangeResult.getStatusCode());
System.out.println("返回结果4:" + exchangeResult.getBody());
}
/**
* 复杂使用
*/
@Test
public void doGetTestTwo() {
String url = "http://localhost:8080/doGetTestWayOne?age={age}";
//方式一:将参数的值存在可变长度参数里,按照顺序进行参数匹配
ResponseEntity<User> responseEntity = restTemplate.getForEntity(url, User.class, 27);
System.out.println("返回结果1:" + responseEntity);
//方式二:将请求参数以键值对形式存储到 Map 集合中,用于请求时URL上的拼接
Map<String, Object> uriVariables = new HashMap<>();
uriVariables.put("age", 101);
User user = restTemplate.getForObject(url, User.class, uriVariables);
System.out.println("返回结果2:" + user);
}
}
Get请求接口
package com.example.demo.controller;
import com.example.demo.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @author lyd
* @Description: Get对应接收示例
* @date 10:38
*/
@RestController
public class GetController {
@Autowired
User user;
@RequestMapping("doGetTestOne")
public Object doGetTestOne() {
user.setName("getOne");
user.setMotto("我命油我不油天");
user.setAge(12);
user.setGender("男");
return user;
}
@RequestMapping("doGetTestWayOne")
public Object doGetTestWayOne(Integer age) {
user.setName("getOne");
user.setMotto("我命油我不油天");
user.setAge(age);
user.setGender("男");
return user;
}
}
Post请求测试类
package com.example.demo.testRestTemplate;
import com.example.demo.pojo.User;
import org.junit.Test;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
/**
* @author lyd
* @Description: Post请求测试类
* @date 11:09
*/
public class TestPost {
RestTemplate restTemplate = new RestTemplate();
@Test
public void doPostTestOne() {
String url = "http://localhost:8080/doPostTestOne";
// 设置请求的 Content-Type 为 application/x-www-form-urlencoded
MultiValueMap<String,String> header = new LinkedMultiValueMap<>();
header.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
/**
* 方式一拼接: 将请求参数值以 K=V 方式用 & 拼接,发送请求使用
*/
// 设置实体类
User user = new User();
user.setName("meimei");
user.setMotto("娇滴滴");
user.setAge(11);
user.setGender("女");
String userStr = "name=" + user.getName() + "&Motto=" + user.getMotto() + "&age=" + user.getAge() + "&Gender=" + user.getGender();
HttpEntity<String> request = new HttpEntity<>(userStr, header);
// RestTemplate设定发送UTF-8编码数据
restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
ResponseEntity<User> exchangeResult = restTemplate.exchange(url, HttpMethod.POST, request, User.class);
System.out.println("返回结果1:"+exchangeResult);
/**
* 方式二:将请求参数以键值对形式存储在 MultiValueMap 集合,发送请求时使用
*/
MultiValueMap<String,Object> map = new LinkedMultiValueMap();
map.add("name","titi");
map.add("age",13);
map.add("gender","女");
map.add("motto","猛男");
HttpEntity<MultiValueMap> request2 = new HttpEntity(map,header);
// RestTemplate设定发送UTF-8编码数据
restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
ResponseEntity<User> exchangeResult2 = restTemplate.exchange(url,HttpMethod.POST, request2, User.class);
System.out.println("返回结果2:"+exchangeResult2);
}
}
Post请求接口
package com.example.demo.controller;
import com.example.demo.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* @author lyd
* @Description: Post对应返回
* @date 11:21
*/
@RestController
public class PostController {
@RequestMapping(value = "doPostTestOne",method = RequestMethod.POST)
public Object doPostTestOne(User user) {
return user;
}
}
文件上传测试类
package com.example.demo.testRestTemplate;
import org.junit.Test;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.util.Collections;
/**
* @author lyd
* @Description: 上传文件测试类
* @date 14:17
*/
public class TestFiles {
RestTemplate restTemplate = new RestTemplate();
@Test
public void testUploadFile() {
String url = "http://localhost:8080/testUploadFile";
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
String filePath = "D:\\IdeaProjects\\test-RestTemplate\\src\\main\\resources\\verifyImg\\1.png";
FileSystemResource fileSystemResource = new FileSystemResource(new File(filePath));
body.add("file", fileSystemResource);
MultiValueMap<String,Object> header = new LinkedMultiValueMap<>();
header.put(HttpHeaders.CONTENT_TYPE, Collections.singletonList(MediaType.MULTIPART_FORM_DATA_VALUE));
HttpEntity<MultiValueMap<String,Object>> requestEntity = new HttpEntity(body,header);
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
System.out.println("upload: " + responseEntity);
}
}
文件上传请求接口
package com.example.demo.controller;
import com.example.demo.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
/**
* @author lyd
* @Description: 文件测试类访问接口
* @date 14:18
*/
@RestController
public class FileController {
@RequestMapping(value = "testUploadFile",method = RequestMethod.POST)
public String testUploadFile(MultipartRequest request) {
// Spring MVC 使用 MultipartRequest 接受带文件的 HTTP 请求
MultipartFile file = request.getFile("file");
String originalFilename = file.getOriginalFilename();
return "upload success filename: " + originalFilename;
}
}
上面用到的实体类
package com.example.demo.pojo;
import lombok.Data;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.stereotype.Component;
/**
* @author lyd
* @Description: 用户实体类
* @date 11:55
*/
@Data
@Component
public class User {
private String name;
private Integer age;
private String gender;
private String motto;
}
项目源码
https://github.com/Wranglery/test-RestTemplate