SpringBoot - 自定义内容协商(HttpMessageConverter)

内容协商:根据客户端接收能力不同,返回不同媒体类型的数据。

 

使返回的数据支持已xml方式返回

 <dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

开启SpringBoot内容协商

localhost:8080/data?format=json

spring:
  mvc:
    contentnegotiation:
      favor-parameter: true #开启请求参数内容协商模式 

 

自定义内容协商

1.自动类协商类

public class MyMessageConverter extends AbstractHttpMessageConverter<ReUser> {
    /**
     * 定义字符编码,防止乱码
     */
    private static final Charset DEFAULT_CHARSET=Charset.forName("UTF-8");
    /**
     * 新建自定义的媒体类型
     */
    public MyMessageConverter(){
        super(new MediaType("application","x-type",DEFAULT_CHARSET));
    }

    /**
     * 表明只处理DemoObj这个类
     */
    @Override
    protected boolean supports(Class<?> aClass) {
        return ReUser.class.isAssignableFrom(aClass);
    }

    /**
     * 重写readInternal方法,处理请求的数据
     */
    @Override
    protected ReUser readInternal(Class<? extends ReUser> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        String temp=StreamUtils.copyToString(httpInputMessage.getBody(),DEFAULT_CHARSET);
        String[] tempArr=temp.split("|");
        return new ReUser(tempArr[0],Integer.parseInt(tempArr[1]));
    }

    /**
     * 重写writeInternal,处理如何输出数据到response
     */
    @Override
    protected void writeInternal(ReUser reUser, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
        String out=reUser.getUsername()+"|"+reUser.getAge();
        StreamUtils.copy(out, DEFAULT_CHARSET, httpOutputMessage.getBody());
    }
}

2.注册自定义协商类

@Configuration(proxyBeanMethods=true)
public class AppConfig {
    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
        return new 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("x-type",MediaType.parseMediaType("application/x-type"));
                //指定支持解析哪些参数对应的哪些媒体类型
                ParameterContentNegotiationStrategy parameterStrategy = new ParameterContentNegotiationStrategy(mediaTypes);
                //parameterStrategy.setParameterName("ff");
                HeaderContentNegotiationStrategy headeStrategy = new HeaderContentNegotiationStrategy();
                configurer.strategies(Arrays.asList(parameterStrategy,headeStrategy));
            }
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(new MyMessageConverter()); } }; } }

 

posted on 2021-12-12 23:09  每天积极向上  阅读(337)  评论(0编辑  收藏  举报

导航