微信小程序支付(java后端)



转自解放号社区:http://bbs.jointforce.com/topic/25765

第一步


进入小程序,下单,请求下单支付,调用小程序登录API来获取Openid( https://mp.weixin.qq.com/debug/w ... .html#wxloginobject ),生成商户订单,这些都是在小程序端完成的业务。

小程序端代码
  1. // pages/pay/pay.js
  2. var app = getApp();
  3. Page({
  4.     data: {},
  5.     onLoad: function (options) {
  6.         // 页面初始化 options为页面跳转所带来的参数
  7.     },
  8.     /* 微信支付 */
  9.     wxpay: function () {
  10.         var that = this
  11.         //登陆获取code
  12.         wx.login({
  13.             success: function (res) {
  14.                 console.log(res.code)
  15.                 //获取openid
  16.                 that.getOpenId(res.code)
  17.             }
  18.         });
  19.     },
  20.     getOpenId: function (code) {
  21.         var that = this;
  22.         wx.request({
  23.             url: "https://api.weixin.qq.com/sns/jscode2session?appid=wxa142513e524e496c&secret=5d6a7d86048884e7c60f84f7aa85253c&js_code=" + code + "&grant_type=authorization_code",
  24.             data: {},
  25.             method: 'GET',
  26.             success: function (res) {
  27.                 console.log('返回openId')
  28.                 console.log(res.data)
  29.                 that.generateOrder(res.data.openid)
  30.             },
  31.             fail: function () {
  32.                 // fail
  33.             },
  34.             complete: function () {
  35.                 // complete
  36.             }
  37.         })
  38.     },
  39.     /**生成商户订单 */
  40.     generateOrder: function (openid) {
  41.         var that = this
  42.         //统一支付
  43.         wx.request({
  44.             url: 'http://localhost:8070/RMS/pay_pay.action',
  45.             method: 'GET',
  46.             data: {
  47.                 total_fee: '5',
  48.                 body: '支付测试',
  49.                 attach:'真假酒水'
  50.             },
  51.             success: function (res) {
  52.                 console.log(res)
  53.                 var pay = res.data
  54.                 //发起支付
  55.                 var timeStamp = pay[0].timeStamp;
  56.                 console.log("timeStamp:"+timeStamp)
  57.                 var packages = pay[0].package;
  58.                 console.log("package:"+packages)
  59.                 var paySign = pay[0].paySign;
  60.                 console.log("paySign:"+paySign)
  61.                 var nonceStr = pay[0].nonceStr;
  62.                  console.log("nonceStr:"+nonceStr)
  63.                 var param = { "timeStamp": timeStamp, "package": packages, "paySign": paySign, "signType": "MD5", "nonceStr": nonceStr };
  64.                 that.pay(param)
  65.             },
  66.         })
  67.     },
  68.     /* 支付   */
  69.     pay: function (param) {
  70.         console.log("支付")
  71.         console.log(param)
  72.         wx.requestPayment({
  73.             timeStamp: param.timeStamp,
  74.             nonceStr: param.nonceStr,
  75.             package: param.package,
  76.             signType: param.signType,
  77.             paySign: param.paySign,
  78.             success: function (res) {
  79.                 // success
  80.                 console.log("支付")
  81.                 console.log(res)
  82.                 wx.navigateBack({
  83.                     delta: 1, // 回退前 delta(默认为1) 页面
  84.                     success: function (res) {
  85.                         wx.showToast({
  86.                             title: '支付成功',
  87.                             icon: 'success',
  88.                             duration: 2000
  89.                         })
  90.                     },
  91.                     fail: function () {
  92.                         // fail
  93.                     },
  94.                     complete: function () {
  95.                         // complete
  96.                     }
  97.                 })
  98.             },
  99.             fail: function (res) {
  100.                 // fail
  101.                 console.log("支付失败")
  102.                 console.log(res)
  103.             },
  104.             complete: function () {
  105.                 // complete
  106.                 console.log("pay complete")
  107.             }
  108.         })
  109.     }
  110. })
复制代码
第二步

调用支付统一下单API来获取prepay_id,并将小程序调起支付数据需要签名的字段appId,timeStamp,nonceStr,package再次签名( https://pay.weixin.qq.com/wiki/d ... ter=7_7&index=3

后台代码
  1. package cn.it.shop.action;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.InputStream;
  4. import java.io.UnsupportedEncodingException;
  5. import java.text.SimpleDateFormat;
  6. import java.util.Date;
  7. import java.util.HashMap;
  8. import java.util.List;
  9. import java.util.Map;
  10. import org.dom4j.Document;
  11. import org.dom4j.DocumentException;
  12. import org.dom4j.Element;
  13. import org.dom4j.io.SAXReader;
  14. import cn.it.shop.util.MessageUtil;
  15. import cn.it.shop.util.PayUtil;
  16. import cn.it.shop.util.PaymentPo;
  17. import cn.it.shop.util.UUIDHexGenerator;
  18. import net.sf.json.JSONArray;
  19. import net.sf.json.JSONObject;
  20. /** 
  21. * @author 
  22. * @version 创建时间:2017年1月21日 下午4:59:03 
  23. * 小程序端请求的后台action,返回签名后的数据传到前台
  24. */
  25. public class PayAction {
  26.     private String total_fee;//总金额
  27.     private String body;//商品描述
  28.     private String detail;//商品详情    
  29.     private String attach;//附加数据
  30.     private String time_start;//交易起始时间
  31.     private String time_expire;//交易结束时间 
  32.     private String openid;//用户标识
  33.     private JSONArray jsonArray=new JSONArray();
  34.     public String pay() throws UnsupportedEncodingException, DocumentException{
  35.          body = new String(body.getBytes("UTF-8"),"ISO-8859-1");  
  36.         String appid = "替换为自己的小程序ID";//小程序ID
  37.         String mch_id = "替换为自己的商户号";//商户号
  38.         String nonce_str = UUIDHexGenerator.generate();//随机字符串
  39.         String today = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
  40.         String code = PayUtil.createCode(8);
  41.         String out_trade_no = mch_id+today+code;//商户订单号
  42.         String spbill_create_ip = "替换为自己的终端IP";//终端IP
  43.         String notify_url = "http://www.weixin.qq.com/wxpay/pay.php";//通知地址
  44.         String trade_type = "JSAPI";//交易类型  
  45.         String openid="替换为用户的openid";//用户标识
  46.         /**/
  47.         PaymentPo paymentPo = new PaymentPo();
  48.         paymentPo.setAppid(appid);
  49.         paymentPo.setMch_id(mch_id);
  50.         paymentPo.setNonce_str(nonce_str);
  51.         String newbody=new String(body.getBytes("ISO-8859-1"),"UTF-8");//以utf-8编码放入paymentPo,微信支付要求字符编码统一采用UTF-8字符编码
  52.         paymentPo.setBody(newbody);
  53.         paymentPo.setOut_trade_no(out_trade_no);
  54.         paymentPo.setTotal_fee(total_fee);
  55.         paymentPo.setSpbill_create_ip(spbill_create_ip);
  56.         paymentPo.setNotify_url(notify_url);
  57.         paymentPo.setTrade_type(trade_type);
  58.         paymentPo.setOpenid(openid);
  59.         // 把请求参数打包成数组
  60.         Map sParaTemp = new HashMap();
  61.         sParaTemp.put("appid", paymentPo.getAppid());
  62.         sParaTemp.put("mch_id", paymentPo.getMch_id());
  63.         sParaTemp.put("nonce_str", paymentPo.getNonce_str());
  64.         sParaTemp.put("body",  paymentPo.getBody());
  65.         sParaTemp.put("out_trade_no", paymentPo.getOut_trade_no());
  66.         sParaTemp.put("total_fee",paymentPo.getTotal_fee());
  67.         sParaTemp.put("spbill_create_ip", paymentPo.getSpbill_create_ip());
  68.         sParaTemp.put("notify_url",paymentPo.getNotify_url());
  69.         sParaTemp.put("trade_type", paymentPo.getTrade_type());
  70.         sParaTemp.put("openid", paymentPo.getOpenid());
  71.         // 除去数组中的空值和签名参数
  72.         Map sPara = PayUtil.paraFilter(sParaTemp);
  73.         String prestr = PayUtil.createLinkString(sPara); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
  74.         String key = "&key=替换为商户支付密钥"; // 商户支付密钥
  75.         //MD5运算生成签名
  76.         String mysign = PayUtil.sign(prestr, key, "utf-8").toUpperCase();
  77.         paymentPo.setSign(mysign);
  78.         //打包要发送的xml
  79.         String respXml = MessageUtil.messageToXML(paymentPo);
  80.         // 打印respXml发现,得到的xml中有“__”不对,应该替换成“_”
  81.         respXml = respXml.replace("__", "_");
  82.         String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";//统一下单API接口链接
  83.         String param = respXml;
  84.         //String result = SendRequestForUrl.sendRequest(url, param);//发起请求
  85.         String result =PayUtil.httpRequest(url, "POST", param);
  86.         // 将解析结果存储在HashMap中
  87.         Map map = new HashMap();
  88.          InputStream in=new ByteArrayInputStream(result.getBytes());  
  89.         // 读取输入流
  90.         SAXReader reader = new SAXReader();
  91.         Document document = reader.read(in);
  92.         // 得到xml根元素
  93.         Element root = document.getRootElement();
  94.         // 得到根元素的所有子节点
  95.         @SuppressWarnings("unchecked")
  96.         List elementList = root.elements();
  97.         for (Element element : elementList) {
  98.             map.put(element.getName(), element.getText());
  99.         }
  100.         // 返回信息
  101.         String return_code = map.get("return_code");//返回状态码
  102.         String return_msg = map.get("return_msg");//返回信息
  103.         System.out.println("return_msg"+return_msg);
  104.         JSONObject JsonObject=new JSONObject() ;
  105.         if(return_code=="SUCCESS"||return_code.equals(return_code)){
  106.             // 业务结果
  107.             String prepay_id = map.get("prepay_id");//返回的预付单信息
  108.             String nonceStr=UUIDHexGenerator.generate();
  109.             JsonObject.put("nonceStr", nonceStr);
  110.             JsonObject.put("package", "prepay_id="+prepay_id);
  111.             Long timeStamp= System.currentTimeMillis()/1000;
  112.             JsonObject.put("timeStamp", timeStamp+"");
  113.             String stringSignTemp = "appId="+appid+"&nonceStr=" + nonceStr + "&package=prepay_id=" + prepay_id+ "&signType=MD5&timeStamp=" + timeStamp;
  114.             //再次签名
  115.             String paySign=PayUtil.sign(stringSignTemp, "&key=替换为自己的密钥", "utf-8").toUpperCase();
  116.             JsonObject.put("paySign", paySign);
  117.             jsonArray.add(JsonObject);
  118.         }
  119.         return "pay";
  120.     }
  121.     public String getTotal_fee() {
  122.         return total_fee;
  123.     }
  124.     public void setTotal_fee(String total_fee) {
  125.         this.total_fee = total_fee;
  126.     }
  127.     public String getBody() {
  128.         return body;
  129.     }
  130.     public void setBody(String body) {
  131.         this.body = body;
  132.     }
  133.     public JSONArray getJsonArray() {
  134.         return jsonArray;
  135.     }
  136.     public void setJsonArray(JSONArray jsonArray) {
  137.         this.jsonArray = jsonArray;
  138.     }
  139.     public String getDetail() {
  140.         return detail;
  141.     }
  142.     public void setDetail(String detail) {
  143.         this.detail = detail;
  144.     }
  145.     public String getAttach() {
  146.         return attach;
  147.     }
  148.     public void setAttach(String attach) {
  149.         this.attach = attach;
  150.     }
  151.     public String getTime_start() {
  152.         return time_start;
  153.     }
  154.     public void setTime_start(String time_start) {
  155.         this.time_start = time_start;
  156.     }
  157.     public String getTime_expire() {
  158.         return time_expire;
  159.     }
  160.     public void setTime_expire(String time_expire) {
  161.         this.time_expire = time_expire;
  162.     }
  163.     public String getOpenid() {
  164.         return openid;
  165.     }
  166.     public void setOpenid(String openid) {
  167.         this.openid = openid;
  168.     }
  169. }
复制代码
后台业务逻辑涉及到的工具类及参数封装类
  1. MessageUtil 
  2. package cn.it.shop.util;
  3. import java.io.IOException;
  4. import java.io.Writer;
  5. import java.util.HashMap;
  6. import java.util.List;
  7. import javax.servlet.http.HttpServletRequest;
  8. import org.dom4j.Document;
  9. import org.dom4j.Element;
  10. import org.dom4j.io.SAXReader;
  11. import com.thoughtworks.xstream.XStream;
  12. import com.thoughtworks.xstream.core.util.QuickWriter;
  13. import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
  14. import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
  15. import com.thoughtworks.xstream.io.xml.XppDriver;
  16. public class MessageUtil {
  17.     public static HashMap parseXML(HttpServletRequest request) throws Exception, IOException{
  18.         HashMap map=new HashMap();
  19.         // 通过IO获得Document
  20.         SAXReader reader = new SAXReader();
  21.         Document doc = reader.read(request.getInputStream());
  22.         //得到xml的根节点
  23.         Element root=doc.getRootElement();
  24.         recursiveParseXML(root,map);
  25.         return map;
  26.     }
  27.     private static void recursiveParseXML(Element root,HashMap map){
  28.         //得到根节点的子节点列表
  29.         List elementList=root.elements();
  30.         //判断有没有子元素列表
  31.         if(elementList.size()==0){
  32.             map.put(root.getName(), root.getTextTrim());
  33.         }
  34.         else{
  35.             //遍历
  36.             for(Element e:elementList){
  37.                 recursiveParseXML(e,map);
  38.             }
  39.         }
  40.     }
  41.     private static XStream xstream = new XStream(new XppDriver() {
  42.         public HierarchicalStreamWriter createWriter(Writer out) {
  43.             return new PrettyPrintWriter(out) {
  44.                 // 对所有xml节点都增加CDATA标记
  45.                 boolean cdata = true;
  46.                 public void startNode(String name, Class clazz) {
  47.                     super.startNode(name, clazz);
  48.                 }
  49.                 protected void writeText(QuickWriter writer, String text) {
  50.                     if (cdata) {
  51.                         writer.write("                        writer.write(text);
  52.                         writer.write("]]>");
  53.                     } else {
  54.                         writer.write(text);
  55.                     }
  56.                 }
  57.             };
  58.         }
  59.     });
  60.     public static String messageToXML(PaymentPo paymentPo){
  61.         xstream.alias("xml",PaymentPo.class);
  62.         return xstream.toXML(paymentPo);
  63.     }
  64. }
  65. PaymentPo//封装支付参数实体
  66. package cn.it.shop.util;
  67. /** 
  68. * @author 
  69. * @version 创建时间:2017年1月21日 下午4:20:52 
  70. * 类说明 
  71. */
  72. public class PaymentPo {
  73.     private String appid;//小程序ID
  74.     private String mch_id;//商户号
  75.     private String device_info;//设备号
  76.     private String nonce_str;//随机字符串
  77.     private String sign;//签名
  78.     private String body;//商品描述  
  79.     private String detail;//商品详情    
  80.     private String attach;//附加数据
  81.     private String out_trade_no;//商户订单号
  82.     private String fee_type;//货币类型
  83.     private String spbill_create_ip;//终端IP
  84.     private String time_start;//交易起始时间
  85.     private String time_expire;//交易结束时间 
  86.     private String goods_tag;//商品标记
  87.     private String total_fee;//总金额
  88.     private String notify_url;//通知地址    
  89.     private String trade_type;//交易类型    
  90.     private String limit_pay;//指定支付方式
  91.     private String openid;//用户标识
  92.     public String getAppid() {
  93.         return appid;
  94.     }
  95.     public void setAppid(String appid) {
  96.         this.appid = appid;
  97.     }
  98.     public String getMch_id() {
  99.         return mch_id;
  100.     }
  101.     public void setMch_id(String mch_id) {
  102.         this.mch_id = mch_id;
  103.     }
  104.     public String getNonce_str() {
  105.         return nonce_str;
  106.     }
  107.     public void setNonce_str(String nonce_str) {
  108.         this.nonce_str = nonce_str;
  109.     }
  110.     public String getSign() {
  111.         return sign;
  112.     }
  113.     public void setSign(String sign) {
  114.         this.sign = sign;
  115.     }
  116.     public String getBody() {
  117.         return body;
  118.     }
  119.     public void setBody(String body) {
  120.         this.body = body;
  121.     }
  122.     public String getOut_trade_no() {
  123.         return out_trade_no;
  124.     }
  125.     public void setOut_trade_no(String out_trade_no) {
  126.         this.out_trade_no = out_trade_no;
  127.     }
  128.     public String getTotal_fee() {
  129.         return total_fee;
  130.     }
  131.     public void setTotal_fee(String total_fee) {
  132.         this.total_fee = total_fee;
  133.     }
  134.     public String getNotify_url() {
  135.         return notify_url;
  136.     }
  137.     public void setNotify_url(String notify_url) {
  138.         this.notify_url = notify_url;
  139.     }
  140.     public String getTrade_type() {
  141.         return trade_type;
  142.     }
  143.     public void setTrade_type(String trade_type) {
  144.         this.trade_type = trade_type;
  145.     }
  146.     public String getOpenid() {
  147.         return openid;
  148.     }
  149.     public void setOpenid(String openid) {
  150.         this.openid = openid;
  151.     }
  152.     public String getSpbill_create_ip() {
  153.         return spbill_create_ip;
  154.     }
  155.     public void setSpbill_create_ip(String spbill_create_ip) {
  156.         this.spbill_create_ip = spbill_create_ip;
  157.     }
  158.     public String getDevice_info() {
  159.         return device_info;
  160.     }
  161.     public void setDevice_info(String device_info) {
  162.         this.device_info = device_info;
  163.     }
  164.     public String getDetail() {
  165.         return detail;
  166.     }
  167.     public void setDetail(String detail) {
  168.         this.detail = detail;
  169.     }
  170.     public String getAttach() {
  171.         return attach;
  172.     }
  173.     public void setAttach(String attach) {
  174.         this.attach = attach;
  175.     }
  176.     public String getFee_type() {
  177.         return fee_type;
  178.     }
  179.     public void setFee_type(String fee_type) {
  180.         this.fee_type = fee_type;
  181.     }
  182.     public String getTime_start() {
  183.         return time_start;
  184.     }
  185.     public void setTime_start(String time_start) {
  186.         this.time_start = time_start;
  187.     }
  188.     public String getTime_expire() {
  189.         return time_expire;
  190.     }
  191.     public void setTime_expire(String time_expire) {
  192.         this.time_expire = time_expire;
  193.     }
  194.     public String getGoods_tag() {
  195.         return goods_tag;
  196.     }
  197.     public void setGoods_tag(String goods_tag) {
  198.         this.goods_tag = goods_tag;
  199.     }
  200.     public String getLimit_pay() {
  201.         return limit_pay;
  202.     }
  203.     public void setLimit_pay(String limit_pay) {
  204.         this.limit_pay = limit_pay;
  205.     }
  206. }
  207. PayUtil
  208. package cn.it.shop.util;
  209. import java.io.BufferedReader;
  210. import java.io.InputStream;
  211. import java.io.InputStreamReader;
  212. import java.io.OutputStream;
  213. import java.io.UnsupportedEncodingException;
  214. import java.net.HttpURLConnection;
  215. import java.net.URL;
  216. import java.util.ArrayList;
  217. import java.util.Collections;
  218. import java.util.HashMap;
  219. import java.util.List;
  220. import java.util.Map;
  221. import org.apache.commons.codec.digest.DigestUtils;
  222. /**
  223. * @author 
  224. * @version 创建时间:2017年1月17日 下午7:46:29 类说明
  225. */
  226. public class PayUtil {
  227.     /**
  228.      * 签名字符串
  229.      * @param text需要签名的字符串
  230.      * @param key 密钥
  231.      * @param input_charset编码格式
  232.      * [url=home.php?mod=space&uid=6711]@return[/url] 签名结果
  233.      */
  234.     public static String sign(String text, String key, String input_charset) {
  235.         text = text + key;
  236.         return DigestUtils.md5Hex(getContentBytes(text, input_charset));
  237.     }
  238.     /**
  239.      * 签名字符串
  240.      *  @param text需要签名的字符串
  241.      * @param sign 签名结果
  242.      * @param key密钥
  243.      * @param input_charset 编码格式
  244.      * @return 签名结果
  245.      */
  246.     public static boolean verify(String text, String sign, String key, String input_charset) {
  247.         text = text + key;
  248.         String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
  249.         if (mysign.equals(sign)) {
  250.             return true;
  251.         } else {
  252.             return false;
  253.         }
  254.     }
  255.     /**
  256.      * @param content
  257.      * @param charset
  258.      * @return
  259.      * @throws SignatureException
  260.      * @throws UnsupportedEncodingException
  261.      */
  262.     public static byte[] getContentBytes(String content, String charset) {
  263.         if (charset == null || "".equals(charset)) {
  264.             return content.getBytes();
  265.         }
  266.         try {
  267.             return content.getBytes(charset);
  268.         } catch (UnsupportedEncodingException e) {
  269.             throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
  270.         }
  271.     }
  272.     /**
  273.      * 生成6位或10位随机数 param codeLength(多少位)
  274.      * @return
  275.      */
  276.     public static String createCode(int codeLength) {
  277.         String code = "";
  278.         for (int i = 0; i < codeLength; i++) {
  279.             code += (int) (Math.random() * 9);
  280.         }
  281.         return code;
  282.     }
  283.     private static boolean isValidChar(char ch) {
  284.         if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
  285.             return true;
  286.         if ((ch >= 0x4e00 && ch <= 0x7fff) || (ch >= 0x8000 && ch <= 0x952f))
  287.             return true;// 简体中文汉字编码
  288.         return false;
  289.     }
  290.     /**
  291.      * 除去数组中的空值和签名参数
  292.      * @param sArray 签名参数组
  293.      * @return 去掉空值与签名参数后的新签名参数组
  294.      */
  295.     public static Map paraFilter(Map sArray) {
  296.         Map result = new HashMap();
  297.         if (sArray == null || sArray.size() <= 0) {
  298.             return result;
  299.         }
  300.         for (String key : sArray.keySet()) {
  301.             String value = sArray.get(key);
  302.             if (value == null || value.equals("") || key.equalsIgnoreCase("sign")
  303.                     || key.equalsIgnoreCase("sign_type")) {
  304.                 continue;
  305.             }
  306.             result.put(key, value);
  307.         }
  308.         return result;
  309.     }
  310.     /**
  311.      * 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串
  312.      * @param params 需要排序并参与字符拼接的参数组
  313.      * @return 拼接后字符串
  314.      */
  315.     public static String createLinkString(Map params) {
  316.         List keys = new ArrayList(params.keySet());
  317.         Collections.sort(keys);
  318.         String prestr = "";
  319.         for (int i = 0; i < keys.size(); i++) {
  320.             String key = keys.get(i);
  321.             String value = params.get(key);
  322.             if (i == keys.size() - 1) {// 拼接时,不包括最后一个&字符
  323.                 prestr = prestr + key + "=" + value;
  324.             } else {
  325.                 prestr = prestr + key + "=" + value + "&";
  326.             }
  327.         }
  328.         return prestr;
  329.     }
  330.     /**
  331.      * 
  332.      * @param requestUrl请求地址
  333.      * @param requestMethod请求方法
  334.      * @param outputStr参数
  335.      */
  336.     public static String httpRequest(String requestUrl,String requestMethod,String outputStr){
  337.         // 创建SSLContext
  338.         StringBuffer buffer=null;
  339.         try{
  340.         URL url = new URL(requestUrl);
  341.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  342.         conn.setRequestMethod(requestMethod);
  343.         conn.setDoOutput(true);
  344.         conn.setDoInput(true);
  345.         conn.connect();
  346.         //往服务器端写内容
  347.         if(null !=outputStr){
  348.             OutputStream os=conn.getOutputStream();
  349.             os.write(outputStr.getBytes("utf-8"));
  350.             os.close();
  351.         }
  352.         // 读取服务器端返回的内容
  353.         InputStream is = conn.getInputStream();
  354.         InputStreamReader isr = new InputStreamReader(is, "utf-8");
  355.         BufferedReader br = new BufferedReader(isr);
  356.         buffer = new StringBuffer();
  357.         String line = null;
  358.         while ((line = br.readLine()) != null) {
  359.                       buffer.append(line);
  360.         }
  361.         }catch(Exception e){
  362.             e.printStackTrace();
  363.         }
  364.         return buffer.toString();
  365.         }   
  366.     public static String urlEncodeUTF8(String source){
  367.         String result=source;
  368.         try {
  369.             result=java.net.URLEncoder.encode(source, "UTF-8");
  370.         } catch (UnsupportedEncodingException e) {
  371.             // TODO Auto-generated catch block
  372.             e.printStackTrace();
  373.         }
  374.         return result;
  375.     }
  376. }
  377. UUIDHexGenerator
  378. package cn.it.shop.util;
  379. import java.net.InetAddress;
  380. /**
  381. * @author 
  382. * @version 创建时间:2017年1月17日 下午7:45:06 类说明
  383. */
  384. public class UUIDHexGenerator {
  385.     private static String sep = "";
  386.     private static final int IP;
  387.     private static short counter = (short) 0;
  388.     private static final int JVM = (int) (System.currentTimeMillis() >>> 8);
  389.     private static UUIDHexGenerator uuidgen = new UUIDHexGenerator();
  390.     static {
  391.         int ipadd;
  392.         try {
  393.             ipadd = toInt(InetAddress.getLocalHost().getAddress());
  394.         } catch (Exception e) {
  395.             ipadd = 0;
  396.         }
  397.         IP = ipadd;
  398.     }
  399.     public static UUIDHexGenerator getInstance() {
  400.         return uuidgen;
  401.     }
  402.     public static int toInt(byte[] bytes) {
  403.         int result = 0;
  404.         for (int i = 0; i < 4; i++) {
  405.             result = (result << 8) - Byte.MIN_VALUE + (int) bytes;
  406.         }
  407.         return result;
  408.     }
  409.     protected static String format(int intval) {
  410.         String formatted = Integer.toHexString(intval);
  411.         StringBuffer buf = new StringBuffer("00000000");
  412.         buf.replace(8 - formatted.length(), 8, formatted);
  413.         return buf.toString();
  414.     }
  415.     protected static String format(short shortval) {
  416.         String formatted = Integer.toHexString(shortval);
  417.         StringBuffer buf = new StringBuffer("0000");
  418.         buf.replace(4 - formatted.length(), 4, formatted);
  419.         return buf.toString();
  420.     }
  421.     protected static int getJVM() {
  422.         return JVM;
  423.     }
  424.     protected synchronized static short getCount() {
  425.         if (counter < 0) {
  426.             counter = 0;
  427.         }
  428.         return counter++;
  429.     }
  430.     protected static int getIP() {
  431.         return IP;
  432.     }
  433.     protected static short getHiTime() {
  434.         return (short) (System.currentTimeMillis() >>> 32);
  435.     }
  436.     protected static int getLoTime() {
  437.         return (int) System.currentTimeMillis();
  438.     }
  439.     public static String generate() {
  440.         return new StringBuffer(36).append(format(getIP())).append(sep).append(format(getJVM())).append(sep)
  441.                 .append(format(getHiTime())).append(sep).append(format(getLoTime())).append(sep)
  442.                 .append(format(getCount())).toString();
  443.     }
  444.     /**
  445.      * @param args
  446.      */
  447.     public static void main(String[] args) {
  448.         String id="";
  449.         UUIDHexGenerator uuid = UUIDHexGenerator.getInstance();
  450.         /*
  451.         for (int i = 0; i < 100; i++) {
  452.             id = uuid.generate();
  453.         }*/
  454.         id = uuid.generate();
  455.         System.out.println(id);
  456.     }
  457. }
复制代码

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值