【问题标题】:POST using RestTemplate, query parameters and request bodyPOST 使用 RestTemplate、查询参数和请求正文
【发布时间】:2018-11-19 23:49:15
【问题描述】:

我正在尝试学习 RestTemplate 并为此制作了两个测试 spring-boot 应用程序,客户端和服务器。在这里询问之前在谷歌上尝试了一些示例,如果我错过了重复的帖子,请见谅。

@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();
}

}

在 ClientController 中,我试图模仿我在 Postman 中所做的事情,但没有运气。

Postman PrintScreen

我做错了什么?谢谢!

【问题讨论】:

  • 你的客户端和服务器是两个不同的应用吗?
  • 是的,两者都是两个独立的项目
  • 问题出在哪里?
  • 显示您遇到的异常或问题?

标签: java rest spring-mvc spring-boot resttemplate


【解决方案1】:

设法弄明白了。不得不这样重构

@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;
}

【讨论】:

    猜你喜欢
    • 2021-09-22
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 2017-09-14
    • 2023-03-19
    相关资源
    最近更新 更多