最近开发微信公众号时测试遇到这个问题,因为公众号发过来的数据是xml,content_type是text/xml
@RequestMapping(value="/message",method= RequestMethod.POST,consumes = {MediaType.TEXT_XML_VALUE},produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public String message( @RequestBody TextMessage message){
log.info("smessage = ",message);
//1. 将token、timestamp、nonce三个参数进行字典序排序
//接入失败
return null;
}
原因应该是springboot默认解析都是json,需要在配置时加上xml的解析支持,并使用合适的MessageConverter
@Configuration @EnableWebMvc public class WebMvcConfig implements WebMvcConfigurer{ @Bean public RequestMappingHandlerAdapter requestMappingHandlerAdapter() { RequestMappingHandlerAdapter adapter = new RequestMappingHandlerAdapter(); List<HttpMessageConverter<?>> converters = adapter.getMessageConverters(); MappingJackson2XmlHttpMessageConverter xmlConverter = new MappingJackson2XmlHttpMessageConverter(); List<MediaType> supportedMediaTypes = new ArrayList<MediaType>(); MediaType xmlMedia = new MediaType(MediaType.TEXT_XML, Charset.forName("UTF-8")); supportedMediaTypes.add(xmlMedia); xmlConverter.setSupportedMediaTypes(supportedMediaTypes); converters.add(xmlConverter); adapter.setMessageConverters(converters); return adapter; }
别忘了,pom.xml上加上
<dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> </dependency>
使用jackon转化xml成对象需要在类上加上注解
package com.davidhu.shopguide.web.model.wechat; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import javax.validation.constraints.NotEmpty; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @JacksonXmlRootElement(localName = "xml") public class TextMessage extends BaseMessage{ public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getMsgId() { return msgId; } public void setMsgId(String msgId) { this.msgId = msgId; } // @XmlElement(name="Content") // @NotEmpty @JacksonXmlProperty(localName = "Content") private String content; // @XmlElement(name="MsgId") // @NotEmpty @JacksonXmlProperty(localName = "MsgId") private String msgId; }