场景:获取网络数据时,发现如下错误
{
"timestamp": "2018-04-13T05:43:23.256+0000",
"status": 500,
"error": "Internal Server Error",
"exception": "feign.codec.DecodeException",
"message": "Could not extract response: no suitable HttpMessageConverter found for response type [class com.alibaba.fastjson.JSONObject] and content type [text/html;charset=UTF-8]",
"path": "/get2"
}
但是,实际上该数据是JSON形式的字符串,只是类型为 text/html 为了解决该问题,可以指定Http的消息转化器,来解析,如下:
1.编写处理类
public class TestHtmlToJsonObjectConver extends AbstractHttpMessageConverter<JSONObject> {
@Autowired
private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter;
/**
* 自定义支持的媒体类型
* 也就是只有此种类型的数据才会被处理
*/
public TestHtmlToJsonObjectConver() {
super(new MediaType("text", "html", Charset.forName("UTF-8")));
}
/**
* 判断是否为支持的类型
*
* @param clazz
* @return
*/
@Override
protected boolean supports(Class<?> clazz) {
return JSONObject.class.isAssignableFrom(clazz);
}
/**
* 用于读取定义的类型的资源,将其转化为JSONObject对象
*
* @param aClass
* @param httpInputMessage
* @return
* @throws IOException
* @throws HttpMessageNotReadableException
*/
@Override
protected JSONObject readInternal(Class<? extends JSONObject> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
String message = StreamUtils.copyToString(httpInputMessage.getBody(), Charset.forName("UTF-8"));
return JSONObject.parseObject(message);
}
/**
* 用于在推送此种类型的资源时,将JSONObject对象转化为自定义的格式返回给调用者
* 这里所有的返回JSONObject对象给前端的请求,都会执行此方法
* 因而调用Spring的默认的mappingJackson2HttpMessageConverter来处理
*
* @param jsonObject
* @param httpOutputMessage
* @throws IOException
* @throws HttpMessageNotWritableException
*/
@Override
protected void writeInternal(JSONObject jsonObject, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
System.out.println("方法被调用");
mappingJackson2HttpMessageConverter.write(jsonObject, new MediaType("application", "*+json"), httpOutputMessage);
}
}
2.件对象注入到容器
@Bean
public TestHtmlToJsonObjectConver testHtmlToJsonObjectConver() {
return new TestHtmlToJsonObjectConver();
}
在Spring boot直接注入到容器,容器就会自动加载该消息转换器而不需要再次注册。当然也可以再次注册
3.注册(非必要)
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
@Bean
public TestHtmlToJsonObjectConver testHtmlToJsonObjectConver() {
return new TestHtmlToJsonObjectConver();
}
/**
* 配置configureMessageConverters默认不加载默认的消息转换器
* 配置extendMessageConverters仅仅添加一个默认的消息转换器,当然也会加载默认的消息转换器
* @param converters
*/
// @Override
// public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// super.configureMessageConverters(converters);
// converters.add(testHtmlToJsonObjectConver());
// }
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
super.extendMessageConverters(converters);
converters.add(testHtmlToJsonObjectConver());
}
}