在这个问题上被难住了一段时间!
从常规 MVC 项目转移到响应式项目,并且正在使用 Spring Boot(新版本 2.0.0.M3)。
在出现这个特殊问题之前,我对整个图书馆的问题为零。
在使用 WebClient 时,我有一个不起作用的请求。它以前与 RestTemplate 一起工作得很好:
rt.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
headers.add("Authorization", "Basic REDACTED");
HttpEntity<OtherApiRequest> entity =
new HttpEntity<OtherApiRequest>(CrawlRequestBuilder.buildCrawlRequest(req), headers);
ResponseEntity<Void> response = rt.postForEntity("https://other_api/path",
entity,
Void.class);
System.out.println(response.getStatusCode());
我的 WebClient 代码:
client
.post()
.uri("https://other_api/path")
.header("Authorization", "Basic REDACTED")
.contentType(MediaType.APPLICATION_JSON)
.body(Mono.just(req), OtherApiRequest.class)
.exchange()
.then(res -> System.out.println(res.getStatusCode()));
我也尝试过先生成身体:
ObjectMapper mapper = new ObjectMapper();
String body = mapper.writeValueAsString(
client
.post()
.uri("https://other_api/path")
.header("Authorization", "Basic REDACTED")
.contentType(MediaType.APPLICATION_JSON)
.body(body, String.class)
.exchange()
.then(res -> System.out.println(res.getStatusCode()));
这里有什么明显的错误吗?我看不出两者之间有任何问题会导致第二个失败......
编辑: RestTemplate 提供 204 的响应。 WebClient 提供 400 的响应,表示正文是无效的 JSON。使用上面 WebClient 的第二个示例,我可以打印body
变量并查看它是正确的 JSON。
Edit2:我正在序列化的 POJO 类:
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class OtherApiRequest {
private String app;
private String urllist;
private int maxDepth;
private int maxUrls;
public OtherApiRequest(String app, String urllist, int maxDepth, int maxUrls) {
this.app = app;
this.urllist = urllist;
this.maxDepth = maxDepth;
this.maxUrls = maxUrls;
}
public String getApp() {
return app;
}
public String getUrllist() {
return urllist;
}
public int getMaxDepth() {
return maxDepth;
}
public int getMaxUrls() {
return maxUrls;
}
public String toString() {
return "OtherApiRequest: {" +
"app: " + app + "," +
"urllist: " + urllist + "," +
"max_depth: " + maxDepth + "," +
"max_urls: " + maxUrls +
"}";
}
}