如何自定义一个 Spring WebClient 实例,以接受
content-type: application/javascript
并反序列化 JSON 响应主体?
我已经使用 WebClient 实现了一个 简单的例子,它使用 CoinDesk API 端点 来实时获取比特币价格指数 (BPI)。
我 重现了错误 用 WireMock 存根端点。
endpoint response body 内容是JSON,然而,它的headers 包含
content-type: application/javascript
,因此WebClient 抛出如下异常:
org.springframework.web.reactive.function.client.WebClientResponseException at WebClientResponseException.java:342
Caused by: org.springframework.web.reactive.function.UnsupportedMediaTypeException at BodyExtractors.java:206
这是声明式客户端实现:
@HttpExchange(url = "/bpi")
public interface BitcoinPriceIndexClient {
@GetExchange(value = "/currentprice.json")
BitcoinCurrentPrice getPriceIndexOnRealTime();
}
@Data
public class BitcoinCurrentPrice {
private BitcoinPriceIndex bpi;
public Price getUsdPrice() {
return bpi.getUsdPrice();
}
public Price getGbpPrice() {
return bpi.getGbpPrice();
}
public Price getEurPrice() {
return bpi.getEurPrice();
}
@Data
@JsonRootName(value = "bpi")
public static class BitcoinPriceIndex {
@JsonProperty("USD")
private Price usdPrice;
@JsonProperty("GBP")
private Price gbpPrice;
@JsonProperty("EUR")
private Price eurPrice;
}
@Data
@JsonNaming(SnakeCaseStrategy.class)
public static class Price {
private Double rateFloat;
}
}
这是客户端的代理创建:
@Bean
BitcoinPriceIndexClient bitcoinPriceIndexClient(WebClient.Builder builder, @Value("${bpi-client.url}") String url) {
var webClient = builder.baseUrl(url).build();
var httpServiceProxyFactory =
HttpServiceProxyFactory.builder(forClient(webClient)).build();
return httpServiceProxyFactory.createClient(BitcoinPriceIndexClient.class);
}
我已经在 spring web-client 上工作了,我们几乎连接到以 JSON 形式提供数据的端点你的响应也看起来像 JSON 响应所以你可以尝试配置
application/json
.