RestTemplate get with body

问题描述 投票:0回答:1

如何利用休息模板制作与身体的get?

基于问题来自 通过JSON中的RestTemplate进行POST请求。我试着通过HttpEntity进行带有body的GET(检查一下是否可以),但是接收失败。

所需的请求体丢失

对于HttpMethod.POST。localhost:8080testpost 体的添加是正确的,但对于HttpMethod.GET 本地主机:8080testget 我的代码是,如下图。

@RestController
@SpringBootApplication
public class DemoApplication {

  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }

  private final RestTemplate restTemplate = new RestTemplate();

  @GetMapping("/test/{api}")
  public SomeObject test(@PathVariable("api") String api) {
    String input = "{\"value\":\"ok\"}";

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> entity = new HttpEntity<>(input, headers);

    HttpMethod method = "get".equals(api) ? HttpMethod.GET : HttpMethod.POST;
    String url = "http://localhost:8080/" + api;
    return restTemplate.exchange(url, method, entity, SomeObject.class).getBody();
  }

  @GetMapping("/get")
  public SomeObject getTestApi(@RequestBody(required = false) SomeObject someObject) {
    return new SomeObject() {{ setValue(someObject != null ? "ok" : "error"); }};
  }

  @PostMapping("/post")
  public SomeObject postTestApi(@RequestBody(required = false) SomeObject someObject) {
    return new SomeObject() {{ setValue(someObject != null ? "ok" : "error"); }};
  }

  @Data
  public static class SomeObject {
    private String value;
  }

}

这是一个完整的例子。https:/gitlab.comartekwichowskigit-with-body

我想知道,代码上有什么问题吗,也是accorging到。HTTP GET的请求体用身体GET是可以的,但就是不好实践。

spring-boot resttemplate
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.