OpenFeignClient Use Object to Receive text/plain Type Return Error

report errors

Could not extract response: no suitable HttpMessageConverter found for
response type [classxxxx] and content type [text/plain]

reason

The return type content type is not application/JSON, but text/plain. It cannot be deserialized into object type, as shown in the figure


spring cloud openfeign essentially uses okhttpclient for request. If it is text/plain, it will be treated as text and cannot be deserialized automatically like JSON string, The following is my feinclient:

in this case, it is necessary to do compatibility processing for the return of this content type
add the jackson2httpmessageconverter conversion class, and increase the compatibility of text/plain and text/HTML return types

import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.util.ArrayList;
import java.util.List;

/**
 * @author <a href="mailto:[email protected]">Tino.Tang</a>
 * @version ${project.version} - 2021/12/9
 */
public class MyJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {

  public LokiJackson2HttpMessageConverter() {
    List<MediaType> mediaTypes = new ArrayList<>();
    mediaTypes.add(MediaType.TEXT_PLAIN);
    mediaTypes.add(MediaType.TEXT_HTML);
    setSupportedMediaTypes(mediaTypes);
  }
}

Add openfeign custom configuration and inject Decoder Bean.

import feign.Logger;
import feign.codec.Decoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author <a href="mailto:[email protected]">Tino.Tang</a>
 * @version ${project.version} - 2021/11/29
 */
@Configuration
public class OpenFeignLogConfig {

  @Bean
  public Logger.Level feignLoggerLeave() {
    return Logger.Level.FULL;
  }

  @Bean
  public Decoder feignDecoder() {
    LokiJackson2HttpMessageConverter converter = new LokiJackson2HttpMessageConverter();
    ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(converter);
    return new SpringDecoder(objectFactory);
  }
}```

After processing, the call to the feign client will no longer report errors, regardless of whether the type is application/json or text/plain, it can be correctly deserialized to Object.

Read More: