【SpringBoot内容协商】

【SpringBoot内容协商】,第1张

基于请求头的内容协商 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 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));
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/877703.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存