1.在springboot中的application.yml配置文件中加上
spring: mvc: contentnegotiation: favor-parameter: true
2.在@bean注解的
WebMvcConfigurer类中重写configureContentNegotiation方法
@Configuration
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
/*
* 配置内容协商策略
* */
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
HashMap<String, MediaType> map = new HashMap<>();
map.put("json", MediaType.APPLICATION_JSON);
map.put("xml", MediaType.APPLICATION_XML);
map.put("awei", MediaType.parseMediaType("application/awei"));
ParameterContentNegotiationStrategy negotiationStrategy = new ParameterContentNegotiationStrategy(map);
configurer.strategies(Arrays.asList(negotiationStrategy));
}
}
}
3.自定义的MessageConverter
package com.example.springbootweb.converter;
import com.example.springbootweb.pojo.Person;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
/*
* 自定义的converter
* */
public class AweiMessageConverter implements HttpMessageConverter<Person> {
@Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
return false;
}
@Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
return clazz.isAssignableFrom(Person.class);
}
/*
* 获取需要的媒体类型
* */
@Override
public List<MediaType> getSupportedMediaTypes() {
return MediaType.parseMediaTypes("application/awei");
}
@Override
public Person read(Class<? extends Person> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
return null;
}
@Override
public void write(Person person, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
//自定义协议数据的写出
String data = person.getPId() + ";" + person.getPName() + ";" + person.getGender() + ";" + person.getAge();
//写出去
OutputStream body = outputMessage.getBody();
//这里需要设置编码类型,否则在浏览器会出现中文乱码
//不能设置utf-8,只能设置GBK
body.write(data.getBytes("GBK"));
}
}
4.在浏览器上通过自定义的数据类型接受数据