服务端接口返回的类型为ModelAndView时,feign客户端调用会报错,原因是因为HttpMessageConverter解析不能解析类型为text/html的数据类型
解决方法:添加text/html解析
代码:
创建转换类:
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
import java.nio.charset.Charset;
public class PayHttpMessageConverter1 extends AbstractHttpMessageConverter<Object> {
public PayHttpMessageConverter1() {
super(MediaType.TEXT_HTML);
}
@Override
protected boolean supports(Class<?> aClass) {
return true;
}
@Override
protected Object readInternal(Class<?> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
String text = StreamUtils.copyToString(httpInputMessage.getBody(), Charset.forName("UTF-8"));
return new ModelAndView(new MyPlainHtmlView(text ));
}
@Override
protected void writeInternal(Object o, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
}
}
解释:将响应流读成字符串,然后将字符串转为ModelAndView
import org.springframework.web.servlet.View;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
public class MyPlainHtmlView implements View {
private final String htmlDocument;
public MyPlainHtmlView(String htmlDocument) {
this.htmlDocument = htmlDocument;
}
@Override
public String getContentType() {
return null;
}
@Override
public void render(Map<String, ?> map, javax.servlet.http.HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
ServletOutputStream out = httpServletResponse.getOutputStream();
out.write(this.htmlDocument.getBytes("utf-8"));
}
}
注意canRead和read就行
在 canRead 方法中判断了是不是 text/html 类型,是的话就会返回true,Spring 就会调用 read,用来将字节流中的数据转换成具体实体,aClass就是我们最终想要得到的实例对象的Class
然后将转换类添加到getMessageConverters中
@Bean
public RestTemplate restTemplate(){
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new PayHttpMessageConverter1());
return restTemplate;
}