Spring boot 将带有标题的请求发送到带有WebClient的第三方api
我非常喜欢我用Spring boot 将带有标题的请求发送到带有WebClient的第三方api,spring-boot,flux,spring-webflux,Spring Boot,Flux,Spring Webflux,我非常喜欢我用restemplate提供的解决方案,但很快它就会随着未来的春季发行而贬值。我正在尝试使用WebClient String text = URLEncoder.encode(text,"UTF-8"); WebClient webClient = WebClient.builder() .baseUrl(BASE_URL) .defaultHeader("Key","af999-e99-4456-b556-4ef
restemplate
提供的解决方案,但很快它就会随着未来的春季发行而贬值。我正在尝试使用WebClient
String text = URLEncoder.encode(text,"UTF-8");
WebClient webClient = WebClient.builder()
.baseUrl(BASE_URL)
.defaultHeader("Key","af999-e99-4456-b556-4ef9947383d")
.defaultHeader("src", srcLang)
.defaultHeader("tgt", tgtLang)
.defaultHeader("text", text)
.build();
然后在此处发送邮件:
Mono<String> response = webClient.post().uri("/google/rtv/text")
.retrieve()
.bodyToMono(String.class);
后来:
java.lang.NullPointerException:null
我试图完成的工作与我使用restemplate
所做的工作类似
像这样:
UriComponentsBuilder builder = UriComponentsBuilder
.fromUriString(URL)
.queryParam("src", src)
.queryParam("tgt", tgt)
.queryParam("text", text);
ResponseEntity<String> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, request, String.class);
建议?问题发生在这里:
root=mapper.readTree(response.toString())代码>
此代码段试图将Mono
序列化为字符串,而Mono
是一种反应类型,最终可以提供该字符串
值
您可以调用<代码>响应.Bug()/<代码>并获得结果<代码>字符串< /> >,但这将是一个阻塞调用,而在反应式执行的中间禁止调用。这样做是有充分理由的,因为这将阻止web应用程序正在使用的少数线程之一,并可能导致它停止服务其他请求
您可以使用类似于:
Mono<String> review = response.map(r -> parseJson(r);
从外观上看,Jackson似乎正在尝试序列化返回的Mono
。你能提供更多的上下文来说明Mono
在哪里使用以及如何使用吗?那么Mono
在哪里使用以及如何使用呢?我这样问是因为问题的根源可能在那里,而不是在您的代码片段中。
UriComponentsBuilder builder = UriComponentsBuilder
.fromUriString(URL)
.queryParam("src", src)
.queryParam("tgt", tgt)
.queryParam("text", text);
ResponseEntity<String> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, request, String.class);
private ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
request.getHeaders().add("Key","af999-e99-4456-b556-4ef9947383d");
ClientHttpResponse response = execution.execute(request, body);
return response;
}
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(Collections.singletonList(this::intercept));
return restTemplate;
}
Mono<String> review = response.map(r -> parseJson(r);
Mono<Review> review = webClient.post().uri("/google/rtv/text")
.retrieve()
.bodyToMono(Review.class);