content-type text/plain feign
处理部分服务返回Content-Type为text-plain
的情况
有些服务例如微信在返回json字符串时的格式并不是application-json
,而是text-plain
。此时如果使用对象接收可能会报错。
如果报错解决办法有两个,一是直接用字符串接收然后手动反序列化;二是通过在配置类中配置Decoder
来处理text-plain
格式。下面为Decoder
配置方法:
/** * 自定义新的decoder来处理微信返回text plain的返回类型 * @return */@Bean public Decoder feignDecoder(){ ObjectFactory<HttpMessageConverters> messageConverters = new ObjectFactory<HttpMessageConverters>() { @Override public HttpMessageConverters getObject() throws BeansException { return new HttpMessageConverters(new MappingJackson2HttpMessageConverter(){ @Override public void setSupportedMediaTypes(List<MediaType> supportedMediaTypes) { List<MediaType> myType = new ArrayList<>(supportedMediaTypes); myType.add(MediaType.TEXT_PLAIN); super.setSupportedMediaTypes(myType); } }); } }; return new SpringDecoder(messageConverters); }
方案2:
import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import java.util.ArrayList; import java.util.List; public class MyJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter { //fegin接收content-type:text/plain 返回体的解决方案 public MyJackson2HttpMessageConverter(){ List<MediaType> mediaTypes = new ArrayList<>(); mediaTypes.add(MediaType.TEXT_PLAIN); setSupportedMediaTypes(mediaTypes); }
@Bean public RequirementClient requirementClient(){ MyJackson2HttpMessageConverter converter =new MyJackson2HttpMessageConverter(); ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(converter); return Feign.builder() .encoder(new JacksonEncoder()) .decoder(new SpringDecoder(objectFactory)) .requestInterceptor(new BasicAuthRequestInterceptor(userName, password, UTF_8)) .target(RequirementClient.class, featureurl); }
https://blog.csdn.net/qq_39107335/article/details/128122780
https://segmentfault.com/a/1190000039427744?utm_source=tag-newest
标签:text,Object,报错,plain,new,import,public From: https://www.cnblogs.com/softidea/p/17115424.html