在这个问题上被难住了一段时间!
从常规的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的响应,表示body是无效的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 +
"}";
}
}发布于 2020-07-14 16:51:31
编辑:
在这里查看更好的答案
Missing Content-Length header sending POST request with WebClient (SpringBoot 2.0.2.RELEASE)
错误报告
https://github.com/spring-projects/spring-framework/issues/21085
已在2.2中修复
当我遇到“无效的JSON响应”时,我通过netcat查看了WebClient请求,并发现实际的有效负载,在本例中为3.16,包含在某种内容信息中:
$ netcat -l 6500
PUT /value HTTP/1.1
user-agent: ReactorNetty/0.7.5.RELEASE
transfer-encoding: chunked
host: localhost:6500
accept-encoding: gzip
Content-Type: application/json
4
3.16
0在我将contentLength()添加到构建器之后,前面的4和后面的0消失了。
https://stackoverflow.com/questions/45644225
复制相似问题