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 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 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 xmlToMap(String strXML) throws Exception {
        try {
            Map data = new HashMap();
            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 xmlToMap(HttpServletRequest request) throws Exception{
        Map map = new HashMap();
        SAXReader reader = new SAXReader();
        InputStream ins = request.getInputStream();
        Document doc = reader.read(ins);

        Element root = doc.getRootElement();
        List list = root.elements();
        for(Element e:list){
            map.put(e.getName(),e.getText());
        }
        ins.close();
        System.out.println(map.toString()   );
        return map;
    }

你可能感兴趣的:(微信公众号小程序)