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{ @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 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> converters) {
converters.add(new GuiguMessageConverter());
}
}
自定义内容协商管理器基于请求头
@Configuration(proxyBeanMethods = false)
public class MyConfig implements WebMvcConfigurer{
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
//Map mediaTypes
Map 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));
}
}



