【发布时间】:2020-09-30 05:25:46
【问题描述】:
如何使用rest模板获取body?
基于来自POST request via RestTemplate in JSON 的问题,我尝试通过 HttpEntity 使用正文进行 GET(只需检查是否可能),但是 接收失败:
缺少必需的请求正文
对于 HttpMethod.POST:localhost:8080/test/post 正文已正确添加,但对于 HttpMethod.GET localhost:8080/test/get 它没有被映射。 我的代码如下:
@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;
}
}
这是带有完整示例的 repo:https://gitlab.com/bartekwichowski/git-with-body
我想知道,代码有什么问题? 另据:HTTP GET with request body GET with body 是可能的,但不是很好的做法。
【问题讨论】:
-
总而言之,localhost:8080/test/get 没有收到您的 RestTemplate 代码发送的正文?
-
是的,就是这样