自定义HttpMessageConverter学习笔记
其他
2021-03-08 20:17:54
阅读次数: 0
实现Content-Type为text/properties媒体类型的HttpMessageConverter
- 编写HttpMessageConverter实现类(核心处理逻辑)
public class PropertiesHttpMessageConverter extends AbstractGenericHttpMessageConverter<Properties> {
public PropertiesHttpMessageConverter(){
super(new MediaType("text", "properties"));
}
@Override
protected void writeInternal(Properties properties, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
OutputStream body = outputMessage.getBody();
Charset charset = this.getCharset(outputMessage) ;
Writer writer = new OutputStreamWriter(body,charset) ;
properties.store(writer,"form PropertiesHttpMessageConverter");
}
@Override
protected Properties readInternal(Class<? extends Properties> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
InputStream body = inputMessage.getBody();
Properties properties = new Properties() ;
Charset charset = getCharset(inputMessage) ;
InputStreamReader reader = new InputStreamReader(body, charset) ;
properties.load(reader);
return properties;
}
private Charset getCharset(HttpMessage inputMessage){
HttpHeaders headers = inputMessage.getHeaders();
MediaType contentType = headers.getContentType();
Charset charset = contentType.getCharset();
charset = charset == null ? Charset.forName("UTF-8") : charset ;
return charset ;
}
@Override
public Properties read(Type type, Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
return readInternal(null, inputMessage);
}
}
- 将自定义HttpMessageConverter添加到RequestMappingHandlerAdapter中
@Configuration
public class RestWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(0,new PropertiesHttpMessageConverter());
}
}
- 编写业务Controller
@RestController
public class PropertiesRestController {
@PostMapping(value = "/add/props",
consumes = "text/properties;charset=UTF-8")
public Properties addProp(@RequestBody Properties properties){
log.info("====> prop : {}" , properties);
return properties ;
}
}
- 使用PostMan发送请求,将Header的Content-Type设置为text/properties
4.1 header内容
Content-Type设置为text/properties
4.1 body内容
username=yicj
addr=北京
转载自blog.csdn.net/yichengjie_c/article/details/114285491