For the Spring org.springframework.web.client.RestTemplate
, it was relatively easy to define an own HttpMessageConverter:
/**
* Set the message body converters to use.
* <p>These converters are used to convert from and to HTTP requests and responses.
*/
public void setMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
validateConverters(messageConverters);
// Take getMessageConverters() List as-is when passed in here
if (this.messageConverters != messageConverters) {
this.messageConverters.clear();
this.messageConverters.addAll(messageConverters);
}
}
When converting my client to an reactive WebClient, I did not find a suitable way to define my own message converter as before with the RestTemplate.
Background: Our spring boot project is based on Scala and we use our own converter (based on com.fasterxml.jackson.module.scala.JacksonModule
) to process Scala Case classes.
You can register custom codecs(Encoder
, Decoder
, HttpMessageReader
, HttpMessageWriter
) via WebClient.builder()
for your WebClient
in the reactive world.
WebClient client = WebClient.builder()
//see: https://github.com/jetty-project/jetty-reactive-httpclient
//.clientConnector(new JettyClientHttpConnector())
.clientConnector(new ReactorClientHttpConnector())
.codecs(
clientCodecConfigurer ->{
// .defaultCodecs() set defaultCodecs for you
// clientCodecConfigurer.defaultCodecs();
// You can customize an encoder based on the defualt config.
// clientCodecConfigurer.defaultCodecs().jackson2Encoder(...)
// Or
// use customCodecs to register Codecs from scratch.
clientCodecConfigurer.customCodecs().register(new Jackson2JsonDecoder());
clientCodecConfigurer.customCodecs().register(new Jackson2JsonEncoder());
}
)
.baseUrl("http://localhost:8080")
.build();
If you're using Spring Boot with WebFlux, you can add a CodecCustomizer
bean, which you can use to register your own custom codecs:
@Bean
CodecCustomizer myCustomCodecCustomizer(...) {
return configurer -> configurer.customCodecs().register(...);
}
By the way, when using Spring Boot with WebMVC, you can just add your HttpMessageConverter
implementation as a bean and it will get picked up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With