使用 RestTemplate、查询参数和请求正文进行 POST



我正在尝试学习RestTemplate,并为此制作了两个测试弹簧启动应用程序,客户端和服务器。在这里询问之前在谷歌上尝试了一些例子,如果我错过了重复的帖子,我很抱歉。

@Slf4j
@RestController
public class ServerController {
@PostMapping("/post")
@ResponseBody
public Resource post(@RequestBody Map<String, String> body,
@RequestParam(name = "path", defaultValue = "NAN") String path) {
if (!body.get("key").equalsIgnoreCase("valid")){
return Resource.builder().ip("'0.0.0.0").scope("KEY NOT VALID").serial(0).build();
}
switch (path) {
case "work":
return Resource.builder().ip("115.212.11.22").scope("home").serial(123).build();
case "home":
return Resource.builder().ip("115.212.11.22").scope("home").serial(456).build();
default:
return Resource.builder().ip("127.0.01").scope("local").serial(789).build();
}
}

}

这是我的客户端控制器

@Slf4j
@RestController
public class ClientController {
@GetMapping("/get")
public Resource get() {
String url = "http://localhost:8085/post";
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAccept(Arrays.asList(MediaType.MULTIPART_FORM_DATA));
httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
body.add("key", "valid");
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(body, httpHeaders);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Resource> response = restTemplate.exchange(url, HttpMethod.POST, entity, Resource.class, Collections.singletonMap("path", "home"));
return response.getBody();
}

}

在客户端控制器中,我试图模仿我在邮递员中所做的,但没有运气。

邮递员打印屏幕

我做错了什么?谢谢!

设法弄清楚了。不得不像这样重构

@GetMapping("/get")
public Resource get(){
String url = "http://localhost:8085/post";
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
.queryParam("path", "home");
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpEntity<Map<String, String>> request = new HttpEntity<Map<String, String>>(Collections.singletonMap("key", "valid"), httpHeaders);
Resource resource = restTemplate.postForObject(builder.toUriString(), request, Resource.class);
return resource;
}

最新更新