浏览器读取的优先顺序
第一优先顺序:text/html -> application/xhtml+xml -> application/xml
第二优先顺序:image/webp -> image/apng
扩展自描述消息
Person
JSON格式(application/json)
请求的参数
{
"id":1,
"name":"啥的却无法"
}
XML 格式(application/xml)
<Person>
<id>1</id>
<name>啥的却无法</name>
</Person>
自定义格式(application/properties+person)
person.id = 1
person.name = 啥的却无法
自定义扩展步骤
1.实现AbstractHttpMessageConverter 抽象类中的方法
public class PropertiesPersonHttpMessageConverter extends
AbstractHttpMessageConverter<Person> {
public PropertiesPersonHttpMessageConverter(){
//自己定义的解析的规则
super(MediaType.valueOf("application/properties+person"));
setDefaultCharset(Charset.forName("UTF-8"));
}
//是否支持当前的POJO类型
@Override
protected boolean supports(Class<?> clazz) {
return clazz.isAssignableFrom(Person.class);
}
/**
* 讲请求内容中 Properties 内容转化成 Person 对象,读取 HTTP 请求中的内容,并且转化成相应的POJO对象(通过 Properties 内容转化成 JSON)
* @param clazz
* @param inputMessage
* @return
* @throws IOException
* @throws HttpMessageNotReadableException
*/
@Override
protected Person readInternal(Class<? extends Person> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
InputStream inputStream=inputMessage.getBody();
Properties properties = new Properties();
// 将请求中的内容转化成Properties
properties.load(new InputStreamReader(inputStream,getDefaultCharset()));
// 将properties 内容转化到 Person 对象字段中
Person person=new Person();
person.setId(Long.valueOf(properties.getProperty("person.id")));
person.setName(properties.getProperty("person.name"));
return person;
}
//将 POJO 的内容序列化成文本内容(Properties格式),最终输出到 HTTP 响应中(通过 JSON 内容转化成 Properties )
@Override
protected void writeInternal(Person person, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
OutputStream outputStream = outputMessage.getBody();
Properties properties = new Properties();
properties.setProperty("person.id",String.valueOf(person.getId()));
properties.setProperty("person.name",person.getName());
properties.store(new OutputStreamWriter(outputStream,getDefaultCharset()),"Written by web server");
}
2.webmvc的配置
实现WebMvcConfigurer
public void extendMessageConverters(
List<HttpMessageConverter<?>> converters) {
converters.add(new PropertiesPersonHttpMessageConverter());
}
3.
@PostMapping(value = "/person/json/to/properties",
produces = "application/properties+person" // 响应类型
)
public Person personJsonToProperties(@RequestBody Person person) {
// @RequestBody 的内容是 JSON
// 响应的内容是 Properties
return person;
}
@PostMapping(value = "/person/properties/to/json",
consumes = "application/properties+person", // 请求类型 // Content-Type
produces = MediaType.APPLICATION_JSON_UTF8_VALUE// 响应类型 // Accept
)
public Person personPropertiesToJson(@RequestBody Person person) {
// @RequestBody 的内容是 Properties
// 响应的内容是 JSON
return person;
}
4.请求的是:/person/properties/to/json
person.id = 1
person.name = 啥的却无法
结果
{
"id":1,
"name":"啥的却无法"
}
另一个结果相反