【SpringBoot内容协商】

基于请求头的内容协商

Accept:Application/xml

【SpringBoot内容协商】_第1张图片

acceptableTypes

【SpringBoot内容协商】_第2张图片

【SpringBoot内容协商】_第3张图片

producibleTypes

【SpringBoot内容协商】_第4张图片

【SpringBoot内容协商】_第5张图片

mediaTypesToUse

【SpringBoot内容协商】_第6张图片

			for (MediaType requestedType : acceptableTypes) {
				for (MediaType producibleType : producibleTypes) {
					if (requestedType.isCompatibleWith(producibleType)) {
						mediaTypesToUse.add(getMostSpecificMediaType(requestedType, producibleType));
					}
				}
			}

【SpringBoot内容协商】_第7张图片

基于请求参数的内容协商

spring:
  mvc:
    contentnegotiation:
      favor-parameter: true
http://localhost:8080/test/person?format=xml

【SpringBoot内容协商】_第8张图片
【SpringBoot内容协商】_第9张图片

自定义内容协商管理器

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 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));
    }
}

你可能感兴趣的:(SpringBoot,spring,boot)