Bootstrap

SpringMVC接收xml格式参数

问题

在对接银行过程中,银行回调时请求参数格式为xml,要求返回格式也为xml(CDATA包裹),利用SpringMVC该怎么处理。

测试

xml格式参数为:

<xml>
  <order_id><![CDATA[201807031109358406949]]></order_id>
  <sign><![CDATA[f296ce56231147869aa413f1edef6403]]></sign>
  <data><![CDATA[{"application_status":"review"}]]></data>
  <uuid><![CDATA[123654978945]]></uuid>
</xml>

提供接受参数的对象

@Data //lombok注解,无需手动添加getter/setter
@XmlRootElement(name = "xml") 
@ToString //lombok注解,无需手动添加toString方法
public class XmlRequest {

    private String order_id;
    private String sign;
    private String data;
    private String uuid;
}

返回参数对象

@Data
@XmlRootElement(name = "xml")
public class XmlResponse {

    private String code;
    private String msg;

    public XmlResponse() {
    }

    public XmlResponse(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }
}

处理xml格式参数接口

    /**
     * 处理xml格式参数
     *
     * @param xmlRequest
     * @return
     */
    @RequestMapping(value = "/handleXmlParam", produces = {"application/xml;charset=UTF-8"})
    @ResponseBody
    public String handleXmlParam(@RequestBody XmlRequest xmlRequest) throws Exception {
        logger.info("XmlRequest:{}", xmlRequest);
        XmlResponse response = new XmlResponse("1", "success");
        return ojbectToXmlWithCDATA(XmlResponse.class, response);
    }

    /**
     * Java对象转换为CDATA包裹XML
     *
     * @param clazz
     * @param obj
     * @return
     * @throws Exception
     */
    public static String ojbectToXmlWithCDATA(Class clazz, Object obj) throws Exception {

        JAXBContext context = JAXBContext.newInstance(clazz);
        // 配置OutputFormat处理CDATA
        OutputFormat of = new OutputFormat();
        of.setCDataElements(new String[]{"^code", "^msg"});
        of.setPreserveSpace(true);
        of.setIndenting(true);
        // 创建序列化
        ByteArrayOutputStream op = new ByteArrayOutputStream();
        XMLSerializer serializer = new XMLSerializer(op, of);
        SAXResult result = new SAXResult(serializer.asContentHandler());
        Marshaller mar = context.createMarshaller();
        mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        mar.marshal(obj, result);

        return op.toString("utf-8");
    }

使用Postman模拟请求,响应也为xml格式 postman模拟xml格式参数请求

日志打印XmlRequest对象,说明参数已经正常接收

XmlRequest:XmlRequest(order_id=m180702762500000201807031109358406949, sign=wxd2a1d0594082a206, data={"application_status":"review"}, uuid=123654978945)

转载于:https://my.oschina.net/LaravelShao/blog/1839949

悦读

道可道,非常道;名可名,非常名。 无名,天地之始,有名,万物之母。 故常无欲,以观其妙,常有欲,以观其徼。 此两者,同出而异名,同谓之玄,玄之又玄,众妙之门。

;