栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【SpringBoot内容协商】

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【SpringBoot内容协商】

基于请求头的内容协商 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 {
    @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 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));
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/872017.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号