Spring Boot接收并响应xml

依赖

1
2
3
4
5
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.7</version>
</dependency>

配置XML转换器

1
2
3
4
5
6
7
8
9
10
@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层

1
2
3
4
@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);

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

对于复杂的xml

比如xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?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>

处理示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@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;
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :