RestTemplate获取正文 [英] RestTemplate get with body
本文介绍了RestTemplate获取正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用REST模板制作Get With Body?
根据POST request via RestTemplate in JSON中的问题,我尝试通过HttpEntity对Body进行Make Get(只检查是否可能),但是 接收失败:缺少必需的请求正文
对于HttpMethod.POST:本地主机:8080/test/post正文已正确添加,但对于 HttpMethod.GETLocalhost: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;
}
}
以下是完整示例的回购:https://gitlab.com/bartekwichowski/git-with-body
我想知道,代码有什么问题? 也适用于:HTTP GET with request body 与身体相处是可能的,但不是很好的练习。
推荐答案
我发现这个记不住了。这不是一种好的做法,但如果在您所处的环境中没有其他机会:
private static final class HttpComponentsClientHttpRequestWithBodyFactory extends HttpComponentsClientHttpRequestFactory {
@Override
protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
if (httpMethod == HttpMethod.GET) {
return new HttpGetRequestWithEntity(uri);
}
return super.createHttpUriRequest(httpMethod, uri);
}
}
private static final class HttpGetRequestWithEntity extends HttpEntityEnclosingRequestBase {
public HttpGetRequestWithEntity(final URI uri) {
super.setURI(uri);
}
@Override
public String getMethod() {
return HttpMethod.GET.name();
}
}
当您获取rest Template对象时
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestWithBodyFactory());
这篇关于RestTemplate获取正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文