基于请求头的内容协商
Accept:Application/xml
acceptableTypes
producibleTypes
mediaTypesToUse
for (MediaType requestedType : acceptableTypes) {
for (MediaType producibleType : producibleTypes) {
if (requestedType.isCompatibleWith(producibleType)) {
mediaTypesToUse.add(getMostSpecificMediaType(requestedType, producibleType));
}
}
}
基于请求参数的内容协商
spring:
mvc:
contentnegotiation:
favor-parameter: true
http://localhost:8080/test/person?format=xml
自定义内容协商管理器
public class GuiguMessageConverter implements HttpMessageConverter<Pet> {
@Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
return false;
}
@Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
return clazz.isAssignableFrom(Pet.class);
}
@Override
public List<MediaType> getSupportedMediaTypes() {
return MediaType.parseMediaTypes("application/x-guigu");
}
@Override
public Pet read(Class<? extends Pet> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
return null;
}
@Override
public void write(Pet pet, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
String s = pet.getName() + ";" + pet.getAge();
OutputStream body = outputMessage.getBody();
body.write(s.getBytes(StandardCharsets.UTF_8));
}
}
@Configuration(proxyBeanMethods = false)
public class MyConfig implements WebMvcConfigurer{
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new GuiguMessageConverter());
}
}
自定义内容协商管理器基于请求头
@Configuration(proxyBeanMethods = false)
public class MyConfig implements WebMvcConfigurer{
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
//Map<String, MediaType> mediaTypes
Map<String, MediaType> mediaTypes = new HashMap<>();
mediaTypes.put("json",MediaType.APPLICATION_JSON);
mediaTypes.put("xml",MediaType.APPLICATION_XML);
mediaTypes.put("gg",MediaType.parseMediaType("application/x-guigu"));
HeaderContentNegotiationStrategy headerStrategy = new HeaderContentNegotiationStrategy();
ParameterContentNegotiationStrategy parameterStrategy = new ParameterContentNegotiationStrategy(mediaTypes);
configurer.strategies(Arrays.asList(parameterStrategy,headerStrategy));
}
}