RestTemplate常用方式
1.Get
1.带请求头
@GetMapping("test00")
public DTO test00(HttpServletRequest request) {
System.out.println(request.getHeaderNames());
DTO dto = new DTO();
dto.setStr("123");
dto.setList(Arrays.asList("1", "2"));
return dto;
}
@Test
public void test00() {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("token", "Bearer 10001");
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(headers);
ResponseEntity<ResponseDTO> responseEntity = restTemplate.exchange("http://localhost:8080/test00", HttpMethod.GET, entity, ResponseDTO.class);
System.out.println(responseEntity.getBody());
}
2.Restful
@GetMapping("test01")
public DTO test01(@RequestParam(name = "name", required = false) String name,
@RequestParam(name = "age", required = false) Integer age) {
System.out.println(name + ", " + age);
DTO dto = new DTO();
dto.setStr("123");
dto.setList(Arrays.asList("1", "2"));
return dto;
}
@Test
public void test01() {
RestTemplate restTemplate = new RestTemplate();
Map<String, Object> map = new HashMap<>();
map.put("name","xiaoming01");
map.put("age",9);
ResponseEntity<ResponseDTO> responseEntity = restTemplate.getForEntity("http://localhost:8080/test01?name={name}&age={age}", ResponseDTO.class, map);
System.out.println(responseEntity.getBody());
}
3.占位符
@GetMapping("test02/{name}/{age}")
public DTO test02(@PathVariable(name = "name", required = false) String name,
@PathVariable(name = "age", required = false) Integer age) {
System.out.println(name + ", " + age);
DTO dto = new DTO();
dto.setStr("123");
dto.setList(Arrays.asList("1", "2"));
return dto;
}
@Test
public void test02() {
RestTemplate restTemplate = new RestTemplate();
Map<String, Object> map = new HashMap<>();
map.put("name","xiaoming02");
map.put("age",9);
ResponseEntity<ResponseDTO> responseEntity = restTemplate.getForEntity("http://localhost:8080/test02/{name}/{age}", ResponseDTO.class, map);
System.out.println(responseEntity.getBody());
}
2.Post
1.表单
@PostMapping("test10")
public DTO test10(@RequestParam(name = "name", required = false) String name,
@RequestParam(name = "age", required = false) Integer age) {
System.out.println(name + ", " + age);
DTO dto = new DTO();
dto.setStr("123");
dto.setList(Arrays.asList("1", "2"));
return dto;
}
@Test
public void test10() {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("name","xiaoming");
map.add("age",9);
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(map, headers);
ResponseEntity<ResponseDTO> responseEntity = restTemplate.postForEntity("http://localhost:8080/test10", entity, ResponseDTO.class);
System.out.println(responseEntity.getBody());
}
2.Json
@Data
static class Person {
String name;
Integer age;
}
@PostMapping("test11")
public DTO test11(@RequestBody Person person) {
System.out.println(person.getName() + ", " + person.getAge());
DTO dto = new DTO();
dto.setStr("123");
dto.setList(Arrays.asList("1", "2"));
return dto;
}
@Test
public void test11() throws JSONException {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
JSONObject param = new JSONObject();
param.put("name", "xiaoming");
param.put("age", 9);
HttpEntity<String> entity = new HttpEntity<>(param.toString(), headers);
ResponseEntity<ResponseDTO> responseEntity = restTemplate.postForEntity("http://localhost:8080/test11", entity, ResponseDTO.class);
System.out.println(responseEntity.getBody());
}
3.上传下载
1.上传
@PostMapping("test20")
public DTO test20(@RequestParam("file") MultipartFile file,
@RequestParam("filename") String filename) {
File folder = new File("C:\\Users\\DELL\\Desktop\\test");
if (!folder.isDirectory()) {
folder.mkdirs();
}
try {
file.transferTo(new File(folder, filename + file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."))));
} catch (IOException e) {
e.printStackTrace();
}
DTO dto = new DTO();
dto.setStr("123");
dto.setList(Arrays.asList("1", "2"));
return dto;
}
@Test
public void test20(){
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("file", new FileSystemResource(new File("C:\\Users\\DELL\\Desktop\\image\\image-20220808224258982.png")));
param.add("filename", "test");
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(param, headers);
ResponseEntity<ResponseDTO> responseEntity = restTemplate.postForEntity("http://localhost:8080/test20", request, ResponseDTO.class);
System.out.println(responseEntity.getBody());
}
2.下载
@GetMapping(value = "test21")
public void test21(@RequestParam(value = "filename") String filename,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
File file = new File("E:\\download" + File.separator + filename);
if (file.exists()) {
FileInputStream fis = new FileInputStream(file);
String extendFileName = filename.substring(filename.lastIndexOf('.'));
response.setContentType(request.getSession().getServletContext().getMimeType(extendFileName));
response.setHeader("content-disposition","attachment;fileName=" + URLEncoder.encode(filename,"UTF-8"));
OutputStream os = response.getOutputStream();
FileCopyUtils.copy(fis,os);
}
}
@Test
public void test21() throws IOException {
RestTemplate restTemplate = new RestTemplate();
String filename = "test.zip";
ResponseEntity<byte[]> rsp = restTemplate.getForEntity("http://localhost:8080/test21?filename={filename}", byte[].class, filename);
System.out.println("文件下载请求结果状态码:" + rsp.getStatusCode());
String targetPath = "C:\\Users\\DELL\\Desktop\\test" + File.separator + filename;
Files.write(Paths.get(targetPath), Objects.requireNonNull(rsp.getBody(), "未获取到下载文件"));
}
@Test
public void test22() {
RestTemplate restTemplate = new RestTemplate();
String filename = "test.zip";
RequestCallback requestCallback = request -> request.getHeaders()
.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));
String targetPath = "C:\\Users\\DELL\\Desktop\\test" + File.separator + filename;
restTemplate.execute("http://localhost:8080/test21?filename={filename}", HttpMethod.GET, requestCallback, clientHttpResponse -> {
Files.copy(clientHttpResponse.getBody(), Paths.get(targetPath));
return null;
}, filename);
}