0

我正在尝试使用 spring-webclient 使用 api。下面是我的代码。代码在 kotlin

webClient.post()
.uri(“some url”)
.body(Mono.just(request))
.retrieve()
**.bodyToMono<UUID>()**
.awaitSingle()

它在下面抛出错误

org.springframework.web.reactive.function.UnsupportedMediaTypeException:bodyType=java.util.UUID 不支持内容类型'text/plain;charset=UTF-8'

如果我试图转换为字符串,它工作正常。下面的代码

webClient.post()
.uri(“some url”)
.body(Mono.just(request))
.retrieve()
**.bodyToMono<String>()**
.awaitSingle()

我期望从 API 得到的响应如下

"response": {
"headers": {
  "Content-Type": "text/plain;charset=UTF-8"
},
"status": 200,
"body": "6ea4c979-5e05-4e72-9007-c4644bef5672"

}

4

1 回答 1

3

You are getting that exception because the response content type is text/plain;charset=UTF-8 and not application/json as stated in the exception message you posted. In the exception message it also says you are trying to parse the response body to a UUID. I am not sure why you want to do it and it will fail because the response body cannot be mapped to a UUID class/object but this is another issue.

So to solve your main issue at the moment, you need to tell Jackson to accept text/plain as it was application/json and for that you need to set the codec in the exchangeStrategies method when building uo the WebClient.

Check the code below, it should fix your issue.

WebClient.builder()
                .baseUrl(BASE_URL)
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .exchangeStrategies(ExchangeStrategies.builder().codecs(this::acceptedCodecs).build())
                .build();


private void acceptedCodecs(ClientCodecConfigurer clientCodecConfigurer) {
        clientCodecConfigurer.customCodecs().register(new Jackson2JsonEncoder(new ObjectMapper(), TEXT_HTML));
        clientCodecConfigurer.customCodecs().register(new Jackson2JsonDecoder(new ObjectMapper(), TEXT_HTML));
    }
于 2020-07-10T20:29:57.647 回答