Spring Boot接收并响应xml

依赖

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

配置XML转换器

@Configuration
public class MessageConverterConfig extends WebMvcConfigurationSupport {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.xml();
        builder.indentOutput(true);
        converters.add(new MappingJackson2XmlHttpMessageConverter(builder.build()));
    }
}

Controller层

@RequestMapping(value = "/creditLoanApplyNotify", method = RequestMethod.POST, consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE)
@ResponseBody
public String creditLoanApplyNotify(@RequestBody CreditLoanApplyNotifyDto req) {
    // 自己逻辑

响应的XML没有xml头

例如:<?xml version="1.0" encoding="UTF-8"?>
起作用的是:xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);

XmlMapper xmlMapper = new XmlMapper();
xmlMapper.setDefaultUseWrapper(false);
xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
String requestBody = xmlMapper.writeValueAsString(req);

对于复杂的xml

比如xml:

<?xml version="1.0" encoding="UTF-8"?>
<document>
    <response>
        <head>
            <appId>wx0001</appId>
            <function>apply.notify</function>
            <inputCharset>UTF-8</inputCharset>
            <reqMsgId>201803300309471966</reqMsgId>
            <reserve>1.0.0.20180621</reserve>
            <respTime>201909191</respTime>
            <respTimeZone>UTC+8</respTimeZone>
            <signType>RSA</signType>
            <version>1.0.0</version>
        </head>
        <body>
            <applyNo>2018033</applyNo>
            <requestId>A</requestId>
            <resultInfo>
                <resultCode>000</resultCode>
                <resultMsg>sign check fail</resultMsg>
                <retry>N</retry>
            </resultInfo>
        </body>
    </response>
    <signature>arfLohOxOIL0BOry==</signature>
</document>

处理示例:

@JacksonXmlRootElement(localName = "document")
@Data
public class CreditLoanApproveAckNotifyDto {
    @JacksonXmlElementWrapper(localName ="response")
    private Response response;
    @JacksonXmlProperty(localName = "signature")
    private String signature;

    @Data
    public class Response {
        @JacksonXmlElementWrapper(localName ="head")
        private Header head;
        @JacksonXmlElementWrapper(localName ="body")
        private NotifyDomain body;
    }
}

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/19/spring-boot-receives-and-responds-to-xml/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
Spring Boot接收并响应xml
依赖 <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifac……
<<上一篇
下一篇>>
文章目录
关闭
目 录