微信支付 MD5加密 、xml转Map/Json 、 Map转xml

来源:互联网 发布:巧克力键盘 知乎 编辑:程序博客网 时间:2024/06/07 11:58

一、MD5加密

public class WxUtils {    private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5","6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };//获取MessageDigest.digest(str) 后的字节数组(数组长度16  范围-128~127)    private static String byteArrayToHexString(byte b[]) {        StringBuffer resultSb = new StringBuffer();        for (int i = 0; i < b.length; i++)            resultSb.append(byteToHexString(b[i]));        return resultSb.toString();    }//对数组中的每个字节进行计算(返回两个字符,最后组成32位密文)    private static String byteToHexString(byte b) {        int n = b;        if (n < 0)            n += 256;        int d1 = n / 16;        int d2 = n % 16;        return hexDigits[d1] + hexDigits[d2];    }//主方法    public static String MD5Encode(String origin, String charsetname) {        String resultString = null;        try {            resultString = new String(origin);            MessageDigest md = MessageDigest.getInstance("MD5");            if (charsetname == null || "".equals(charsetname))            //执行md.digest(byte []bytes)过程中,会先执行 update,将字符串的bytes数组加入进程 md.digest(bytes) 返回长度为16的字节数组                resultString =                 byteArrayToHexString(md.digest(resultString                        .getBytes()));            else                resultString = byteArrayToHexString(md.digest(resultString                        .getBytes(charsetname)));        } catch (Exception exception) {        }        return resultString;    } public static void main(String args[]){        WxUtils.MD5Encode("hello","utf-8");    }}

注意:编码格式在没有中文情况下得到的结果是一样的,在有中文的情况下编码格式会影响最后结果,微信sign签名方式为 utf-8 编码格式

二、xml 转 Map/Json (json为例)

package com.wxpay.utils;import net.sf.json.JSONObject;import org.dom4j.Attribute;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;import org.springSupport.utils.Md5Util;import java.io.ByteArrayInputStream;import java.io.InputStream;import java.security.MessageDigest;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;public class Test {    public JSONObject xmlToMap(Element node) throws DocumentException {        JSONObject jsonObject = new JSONObject();        System.out.println("节点的名称:" + node.getName());        //首先获取当前节点的所有属性节点        List<Attribute> list = node.attributes();        //遍历属性节点        for(Attribute attribute : list){            System.out.println("属性"+attribute.getName() +":" + attribute.getValue());        }        //如果当前节点内容不为空,则输出        if(!(node.getTextTrim().equals(""))){            System.out.println( node.getName() + ":" + node.getText());            jsonObject.put(node.getName(),node.getText());        }        //同时迭代当前节点下面的所有子节点        //使用递归        Iterator<Element> iterator = node.elementIterator();        while(iterator.hasNext()){            Element e = iterator.next();            xmlToMap(e);        }        return jsonObject;    }    public static void main(String []args) throws DocumentException {        //创建SAXReader对象        SAXReader reader = new SAXReader();        InputStream is = new ByteArrayInputStream("<xml><id>1</id><name>frank</name></xml>".getBytes());        //读取文件 转换成Document        Document document = reader.read(is);        //获取根节点元素对象        Element root = document.getRootElement();        Test t = new Test();        t.xmlToMap(root);    }}

输出结果,如图:

这里写图片描述

三、Map 转 xml

package com.wxpay.utils;import net.sf.json.JSONObject;import org.apache.commons.lang.StringUtils;import org.dom4j.Attribute;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;import org.springSupport.utils.Md5Util;import java.io.ByteArrayInputStream;import java.io.InputStream;import java.security.MessageDigest;import java.util.*;public class Test {    /**     *  map转成xml     * @param parm     * @param isAddCDATA     * @return     */    public String mapToXml(Map<String, String> parm, boolean isAddCDATA) {//首先要对map进行ASCLL码排序        ArrayList<Map.Entry<String,String>> arrayList = new ArrayList<>(parm.entrySet());        Collections.sort(arrayList, new Comparator<Map.Entry<String, String>>() {            @Override            public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {                return o1.getKey().compareTo(o2.getKey());            }        });        StringBuffer strbuff = new StringBuffer("<xml>");        if (parm != null && !parm.isEmpty()) {            for (Map.Entry<String, String> entry : arrayList) {                strbuff.append("<").append(entry.getKey()).append(">");                if (isAddCDATA) {                    strbuff.append("<![CDATA[");                    if (StringUtils.isNotEmpty(entry.getValue())) {                        strbuff.append(entry.getValue());                    }                    strbuff.append("]]>");                } else {                    if (StringUtils.isNotEmpty(entry.getValue())) {                        strbuff.append(entry.getValue());                    }                }                strbuff.append("</").append(entry.getKey()).append(">");            }        }        return strbuff.append("</xml>").toString();    }    public static void main(String []args) throws DocumentException {        Map<String,String> map = new HashMap<>();        map.put("appid","11111111111111");        map.put("mch_id","222222222222");        map.put("body","测试");        map.put("sign_type","MD5");        Test t = new Test();//是否添加CDATA标签,false为否        System.out.println(t.mapToXml(map,false));    }}

输出结果,如图

这里写图片描述

原创粉丝点击