Spring获取公众号xml数据的两种方式

方式1:HttpServletRequest req

    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(HTTPServletRequest req,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam("openid") String openid,
                       @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature) {

        logger.info("notifyData"+requestData,requestData.toString());
        logger.info("post:{},{},{},{},{}",signature,timestamp,nonce,openid,encType,msgSignature);
        if (!CheckUtil.checkSignature(signature, timestamp, nonce)) {
            throw new IllegalArgumentException("非法请求!");
        }
        Map<String, String> map = null;
        try {
          map = MessageUtil.xmlToMap(req);
            wxAccountService.router(map,openid);
            System.out.println(openid);
        } catch (Exception e) {
            e.printStackTrace();
        }
    return  "";

    }

方式2:@RequestBody

requestData任意命名,即可把body中的xml数据转换为xml字符串。

    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@RequestBody String requestData,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam("openid") String openid,
                       @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature) {

        logger.info("notifyData"+requestData,requestData.toString());
        logger.info("post:{},{},{},{},{}",signature,timestamp,nonce,openid,encType,msgSignature);
        if (!CheckUtil.checkSignature(signature, timestamp, nonce)) {
            throw new IllegalArgumentException("非法请求!");
        }
        Map<String, String> map = null;
        try {
            map = WXPayUtil.xmlToMap(requestData);
//          map = MessageUtil.xmlToMap(req);
            wxAccountService.router(map,openid);
            System.out.println(openid);
        } catch (Exception e) {
            e.printStackTrace();
        }
    return  "";

    }

附赠转换工具

    public static Map<String, String> xmlToMap(String strXML) throws Exception {
        try {
            Map<String, String> data = new HashMap<String, String>();
            DocumentBuilder documentBuilder = WXPayXmlUtil.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                // do nothing
            }
            return data;
        } catch (Exception ex) {
            WXPayUtil.getLogger().warn("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(), strXML);
            throw ex;
        }

    }
     * 利用dom4j读取xml文件存放在map对象中
     */
    public static Map<String,String> xmlToMap(HttpServletRequest request) throws Exception{
        Map<String,String> map = new HashMap<String, String>();
        SAXReader reader = new SAXReader();
        InputStream ins = request.getInputStream();
        Document doc = reader.read(ins);

        Element root = doc.getRootElement();
        List<Element> list = root.elements();
        for(Element e:list){
            map.put(e.getName(),e.getText());
        }
        ins.close();
        System.out.println(map.toString()   );
        return map;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值