How to make get with body using rest template?
Based on question from: POST request via RestTemplate in JSON, I tried make GET with body via HttpEntity (just check if it is possible), but it failed receiving:
Required request body is missing
For HttpMethod.POST: localhost:8080/test/post body is added correctly, but for HttpMethod.GET localhost:8080/test/get it is not mapped. My code is, as below:
@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;
}
}
Here is the repo with full example: https://gitlab.com/bartekwichowski/git-with-body
I wonder, what is wrong with code? Also accorging to: HTTP GET with request body GET with body is possible, but just not good practice.