Bar*_*tek 5 resttemplate spring-boot
如何使用休息模板来获取身体?
基于以下问题:POST request via RestTemplate in JSON,我尝试通过 HttpEntity 使用 body 进行 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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是带有完整示例的存储库:https ://gitlab.com/bartekwichowski/git-with-body
我想知道,代码有什么问题吗?还根据:HTTP GET with request body GET with body 是可能的,但这不是一个好的做法。
小智 -2
我对 RestTemplate 和 GET 也有同样的问题。
尝试切换到 Unirest,但这也不允许将 body 与 GET 方法一起使用。
将 GET 更改为 POST 成功。
在 Liberty 中部署后,从邮递员处拨打电话工作正常,正文确实被接受并生成了预期的响应。
我相信它与所使用的嵌入式 tomcat 服务器有关。
归档时间: |
|
查看次数: |
16674 次 |
最近记录: |