如何使用休息模板来获取身体?
基于以下问题:通过 JSON 格式的 RestTemplate 进行 POST 请求 https://stackoverflow.com/questions/4075991/post-request-via-resttemplate-in-json,我尝试通过 HttpEntity 使用 body 进行 GET (只需检查是否可能),但是
接收失败:
缺少必需的请求正文
对于 HttpMethod.POST:本地主机:8080/测试/发布主体已正确添加,但对于
HttpMethod.GET本地主机:8080/测试/获取它没有被映射。
我的代码如下:
@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 https://gitlab.com/bartekwichowski/git-with-body
我想知道,代码有什么问题吗?
还根据:带请求正文的 HTTP GET https://stackoverflow.com/questions/978061/http-get-with-request-bodyGET with 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();
}
}
当你得到你的restTemplate对象时
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestWithBodyFactory());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)