java微信小程序支付接口

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36596988/article/details/80011383

利用的是java maven 框架ssm

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>cn</groupId>
  <artifactId>wechatdemo</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>wechatdemo Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

		<!-- spring版本号 -->
		<spring.version>4.3.9.RELEASE</spring.version>

		<!-- mybatis版本号 -->
		<mybatis.version>3.4.4</mybatis.version>

		<!-- mysql驱动版本号 -->
		<mysql-driver.version>6.0.6</mysql-driver.version>

		<!-- log4j日志包版本号 -->
		<slf4j.version>1.7.25</slf4j.version>
		<log4j.version>1.2.17</log4j.version>
	</properties>

	<dependencies>

		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.3.1</version>
		</dependency>
		<dependency>
			<groupId>org.jdom</groupId>
			<artifactId>jdom</artifactId>
			<version>1.1.3</version>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>

		<!-- 添加jstl依赖 -->
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.1.0</version>
		</dependency>

		<!--spring -->
		<!-- 添加spring核心依赖 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<!-- <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> 
			<version>${spring.version}</version> </dependency> -->
		<!-- <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> 
			<version>${spring.version}</version> </dependency> -->

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-oxm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<!-- <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> 
			<version>${spring.version}</version> </dependency> -->

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> 
			<version>${spring.version}</version> </dependency> -->

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- 添加mybatis依赖 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${mybatis.version}</version>
		</dependency>

		<!-- 添加mybatis/spring整合包依赖 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.3.0</version>
		</dependency>

		<!-- 添加mysql驱动依赖 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql-driver.version}</version>
		</dependency>

		<!--c3p0连接池 -->
		<!--<dependency> -->
		<!--<groupId>com.mchange</groupId> -->
		<!--<artifactId>c3p0</artifactId> -->
		<!--<version>0.9.5.2</version> -->
		<!--</dependency> -->

		<!--bonecp连接池 -->
		<dependency>
			<groupId>com.jolbox</groupId>
			<artifactId>bonecp-spring</artifactId>
			<version>0.8.0.RELEASE</version>
		</dependency>

		<!-- 添加日志相关jar包 -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>

		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>2.8.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
			<version>2.8.2</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
		</dependency>


		<dependency>
			<groupId>aopalliance</groupId>
			<artifactId>aopalliance</artifactId>
			<version>1.0</version>
		</dependency>

		<dependency>
			<groupId>org.ow2.asm</groupId>
			<artifactId>asm</artifactId>
			<version>5.2</version>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.8.11</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/cglib/cglib -->
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>3.2.5</version>
		</dependency>

		<!--jackson -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.9.1</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.javassist/javassist -->
		<dependency>
			<groupId>org.javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.22.0-GA</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.8.3</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.5</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>

	</dependencies>
	<build>
		<plugins>
			<!-- define the project compile level -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
		</plugins>
		<finalName>wechatdemo</finalName>
		<resources>
			<resource>
				<!--需要打包的目录 -->
				<directory>src/main/java</directory>
				<!--目录中的文件类型 -->
				<includes>
					<include>**/*.xml</include>
					<include>**/*.properties</include>
				</includes>
			</resource>
			<resource>
				<!--需要打包的目录 -->
				<directory>src/main/resources</directory>
				<!--目录中的文件类型 -->
				<includes>
					<include>**/*.xml</include>
					<include>**/*.properties</include>
				</includes>
			</resource>
		</resources>
	</build>
</project>

以下是代码内容

首先微信小程序调用一个方法(这个方法写在java里 第二步会写到) 这个方法要返回paysign等

  wx.request({
      url: "你的IP地址"+ "order/returnparam.action",//调用java后台的方法
      data: {
        'openid': "获取用户的openid",//需要你获取用户的openid
        'title': "shoplist",//订单名称 这里随便定义shoplist
        'price': 0.1* 100,//一毛钱
        'goodsid': 100,///商品ID 这里随便定义成100
      },
      method: 'POST',
      header: {
        "content-type": 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.requestPayment({
          timeStamp: res.data.timeStamp,
          nonceStr: res.data.nonceStr,
          package: res.data.package,
          signType: res.data.signType,
          paySign: res.data.paySign,
          success: function (res) {
            console.log("付款成功")
          },
          fail: function (res) {
            console.log("付款失败")
          }
        })

      }
    })

第二步 支付方法 

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.Gson;

import cn.myutils.HttpUtil;
import cn.myutils.MyResponseJson;
import cn.myutils.PayCommonUtil;
import cn.myutils.XMLUtil;
import redis.clients.jedis.Jedis;

@Controller
@RequestMapping("order")
public class OrderController {
	private static Logger logger = Logger.getLogger(OrderController.class);
	/*
	 * 购买
	 * @param request
	 * @param response
	 * @return
	 * */
	
	@ResponseBody
	@RequestMapping("returnparam")
	public void doOrder(HttpServletRequest request, HttpServletResponse response) throws Exception{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		//得到openid(微信用户唯一的openid)
		String openid = request.getParameter("openid");
		//得到价钱(自定义)
		int fee = 0;
		if (null != request.getParameter("price")) {
			fee = Integer.parseInt(request.getParameter("price").toString());
		}
		//得到商品的ID(自定义)
		String goodsid=request.getParameter("goodsid");
		//订单标题(自定义)
		String title = request.getParameter("title");
		//时间戳
		String times = System.currentTimeMillis() + "";
		
		//订单编号(自定义 这里以时间戳+随机数)
		Random random = new Random();
		String did = times+random.nextInt(1000);

		SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
		packageParams.put("appid", "微信小程序ID");//微信小程序ID
		packageParams.put("mch_id", "商户ID");//商户ID
		packageParams.put("nonce_str", times);//随机字符串(32位以内) 这里使用时间戳
		packageParams.put("body", title);//支付主体名称 自定义
		packageParams.put("out_trade_no", did+goodsid);//编号 自定义以时间戳+随机数+商品ID
		packageParams.put("total_fee", fee);//价格 自定义
		//packageParams.put("spbill_create_ip", remoteAddr);
		packageParams.put("notify_url", "http://你的IP地址/order/buy.action");//支付返回地址要外网访问的到, localhost不行,调用下面buy方法。(订单存入数据库)
		packageParams.put("trade_type", "JSAPI");//这个api有,固定的
		packageParams.put("openid", openid);//用户的openid 可以要 可以不要
		//获取sign
		String sign = PayCommonUtil.createSign("UTF-8", packageParams, "32位秘钥");//最后这个是自己在微信商户设置的32位密钥
		packageParams.put("sign", sign);
		System.out.println(sign);
		//转成XML
		String requestXML = PayCommonUtil.getRequestXml(packageParams);
		System.out.println(requestXML);
		//得到含有prepay_id的XML
		String resXml = HttpUtil.postData("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXML);
		System.out.println(resXml);
		//解析XML存入Map
		Map map = XMLUtil.doXMLParse(resXml);
		System.out.println(map);
		// String return_code = (String) map.get("return_code");
		//得到prepay_id
		String prepay_id = (String) map.get("prepay_id");
		SortedMap<Object, Object> packageP = new TreeMap<Object, Object>();
		packageP.put("appId", "微信小程序ID");//!!!注意,这里是appId,上面是appid
		packageP.put("nonceStr", times);//时间戳
		packageP.put("package", "prepay_id=" + prepay_id);//必须把package写成 "prepay_id="+prepay_id这种形式
		packageP.put("signType", "MD5");//paySign加密
		packageP.put("timeStamp", (System.currentTimeMillis() / 1000) + "");
		//得到paySign
		String paySign = PayCommonUtil.createSign("UTF-8", packageP, "32位秘钥");
		packageP.put("paySign", paySign);
		//将packageP数据返回给小程序
		Gson gson = new Gson();
		String json = gson.toJson(packageP);
		PrintWriter pw = response.getWriter();
		System.out.println(json);
		pw.write(json);
		pw.close();
	}
	//订单存入数据库  上面参数 packageParams.put("notify_url", "http://你的IP地址/order/buy.action");回调的就是这个方法
	@RequestMapping(value="buy")
	@ResponseBody
	public void Buy(HttpServletRequest request,HttpServletResponse response) throws Exception{

		BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));  
		String line = null;  
		StringBuilder sb = new StringBuilder();  
		while((line = br.readLine()) != null){  
			sb.append(line);  
		}  
		br.close();  
		//sb为微信返回的xml  
		String notityXml = sb.toString();  
		String resXml = "";  
		Map map = XMLUtil.doXMLParse(notityXml);
		String returnCode = (String) map.get("return_code");  

		if("SUCCESS".equals(returnCode)){  
			String out_trade_no=(String) map.get("out_trade_no");
			String timestamp=(String) map.get("nonce_str");
			String goodsid=out_trade_no.substring(out_trade_no.length()-3, out_trade_no.length());
			String openid=(String) map.get("openid");
			/*
			 * 
			 * 
			 * 
			 * 
			 * 
			 * 自己写存入数据库的逻辑
			 * 
			 * 
			 * 
			 * 
			 * 
			 * 
			 * 
			 * */
			resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"  
					+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";  
		}else {
			resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"  
					+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";  
		}
		BufferedOutputStream out = new BufferedOutputStream(  
				response.getOutputStream());  
		out.write(resXml.getBytes());  
		out.flush();  
		out.close();  

	}
}
以上的逻辑就是 微信小程序调用java后台方法获取参数->java后台设置参数等等并且传参数回去给微信小程序->微信小程序支付成功->调用你设置的回调地址(订单传入数据库)->最后在调用微信小程序的success方法

需要工具类

package cn.myutils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

public class HttpUtil {
    //private static final Log logger = Logs.get();  
       private final static int CONNECT_TIMEOUT = 5000; // in milliseconds  
       private final static String DEFAULT_ENCODING = "UTF-8";  

       public static String postData(String urlStr, String data){  
           return postData(urlStr, data, null);  
       }  

       public static String postData(String urlStr, String data, String contentType){  
           BufferedReader reader = null;  
           try {  
               URL url = new URL(urlStr);  
               URLConnection conn = url.openConnection();  
               conn.setDoOutput(true);  
               conn.setConnectTimeout(CONNECT_TIMEOUT);  
               conn.setReadTimeout(CONNECT_TIMEOUT);  
               if(contentType != null)  
                   conn.setRequestProperty("content-type", contentType);  
               OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);  
               if(data == null)  
                   data = "";  
               writer.write(data);   
               writer.flush();  
               writer.close();    

               reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));  
               StringBuilder sb = new StringBuilder();  
               String line = null;  
               while ((line = reader.readLine()) != null) {  
                   sb.append(line);  
                   sb.append("\r\n");  
               }  
               return sb.toString();  
           } catch (IOException e) {  
               //logger.error("Error connecting to " + urlStr + ": " + e.getMessage());  
           } finally {  
               try {  
                   if (reader != null)  
                       reader.close();  
               } catch (IOException e) {  
               }  
           }  
           return null;  
       }  
}
package cn.myutils;

import java.security.MessageDigest;

public class MD5 {
    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();
    }

    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))
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes()));
            else
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes(charsetname)));
        } catch (Exception exception) {
        }
        return resultString;
    }

    private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
        "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

}

package cn.myutils;

import java.util.Date;

/**
* @author	lastlySly 
* @create	2018年3月6日 下午10:26:43 
* Description: 
*/
public class MyExceptionOutLog {
	public static String outLog(Exception e) {
		String error = "";
		StackTraceElement[] st = e.getStackTrace();
		for (StackTraceElement stackTraceElement : st) {
			String exclass = stackTraceElement.getClassName();
			String method = stackTraceElement.getMethodName();
			/*new Date() + ":" + */
			error += "\t[类:" + exclass + "]调用"
			+ method + "时在第" + stackTraceElement.getLineNumber()
			+ "行代码处发生异常!\n\t\t\t异常类型:" + e.getClass().getName()
			+ "\n\t\t异常信息为:"+ e.toString()+"\n";
		}
		
		return error;
	}
}

package cn.myutils;

/**
* @author	lastlySly 
* @create	2018年3月5日 下午10:20:25 
* Description: 输出规范
*/
public class MyResponseJson {
	public int code;
	public String tip;
	public Object data;
	
	public MyResponseJson() {
		super();
		// TODO Auto-generated constructor stub
	}
	public MyResponseJson(int code, String tip, Object data) {
		super();
		this.code = code;
		this.tip = tip;
		this.data = data;
	}
	public int getCode() {
		return code;
	}
	public void setCode(int code) {
		this.code = code;
	}
	public String getTip() {
		return tip;
	}
	public void setTip(String tip) {
		this.tip = tip;
	}
	public Object getData() {
		return data;
	}
	public void setData(Object data) {
		this.data = data;
	}

	
}

package cn.myutils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

public class PayCommonUtil {
	/** 
	 * 是否签名正确,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。 
	 * @return boolean 
	 */  
	public static boolean isTenpaySign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {  
		StringBuffer sb = new StringBuffer();  
		Set es = packageParams.entrySet();  
		Iterator it = es.iterator();  
		while(it.hasNext()) {  
			Map.Entry entry = (Map.Entry)it.next();  
			String k = (String)entry.getKey();  
			String v = (String)entry.getValue();  
			if(!"sign".equals(k) && null != v && !"".equals(v)) {  
				sb.append(k + "=" + v + "&");  
			}  
		}  

		sb.append("key=" + API_KEY);  

		//算出摘要  
		String mysign = MD5.MD5Encode(sb.toString(), characterEncoding).toLowerCase();  
		String tenpaySign = ((String)packageParams.get("sign")).toLowerCase();  

		//System.out.println(tenpaySign + "    " + mysign);  
		return tenpaySign.equals(mysign);  
	}  

	/** 
	 * @author 
	 * @Description:sign签名 
	 * @param characterEncoding 
	 *            编码格式 
	 * @param parameters 
	 *            请求参数 
	 * @return 
	 */  
	public static String createSign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {  
		StringBuffer sb = new StringBuffer();  
		Set es = packageParams.entrySet();  
		Iterator it = es.iterator();  
		while (it.hasNext()) {  
			Map.Entry entry = (Map.Entry) it.next();  
			String k = entry.getKey().toString();  
			String v = entry.getValue().toString();  
			if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {  
				sb.append(k + "=" + v + "&");  
			}  
		}  
		sb.append("key=" + API_KEY);  
		String sign = MD5.MD5Encode(sb.toString(), characterEncoding).toUpperCase();  
		return sign;  
	}  
	public static String createLinkString(Map<String, String> params) {     
		List<String> keys = new ArrayList<String>(params.keySet());     
		Collections.sort(keys);     
		String prestr = "";     
		for (int i = 0; i < keys.size(); i++) {     
			String key = keys.get(i);     
			String value = params.get(key);     
			if (i == keys.size() - 1) {// 拼接时,不包括最后一个&字符     
				prestr = prestr + key + "=" + value;     
			} else {     
				prestr = prestr + key + "=" + value + "&";     
			}     
		}     
		return prestr;     
	}     
	/** 
	 * @author 
	 * @Description:将请求参数转换为xml格式的string 
	 * @param parameters 
	 *            请求参数 
	 * @return 
	 */  
	public static String getRequestXml(SortedMap<Object, Object> parameters) {  
		StringBuffer sb = new StringBuffer();  
		sb.append("<xml>");  
		Set es = parameters.entrySet();  
		Iterator it = es.iterator();  
		while (it.hasNext()) {  
			Map.Entry entry = (Map.Entry) it.next();  
			String k = entry.getKey().toString();  
			String v = entry.getValue().toString();   
			if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {  
				sb.append("<" + k + ">"  + v + "</" + k + ">");  
			} else {  
				sb.append("<" + k + ">" + v + "</" + k + ">");  
			}  
		}  
		sb.append("</xml>");  
		return sb.toString();  
	}  

	/** 
	 * 取出一个指定长度大小的随机正整数. 
	 *  
	 * @param length 
	 *            int 设定所取出随机数的长度。length小于11 
	 * @return int 返回生成的随机数。 
	 */  
	public static int buildRandom(int length) {  
		int num = 1;  
		double random = Math.random();  
		if (random < 0.1) {  
			random = random + 0.1;  
		}  
		for (int i = 0; i < length; i++) {  
			num = num * 10;  
		}  
		return (int) ((random * num));  
	}  

	/** 
	 * 获取当前时间 yyyyMMddHHmmss 
	 *  
	 * @return String 
	 */  
	public static String getCurrTime() {  
		Date now = new Date();  
		SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");  
		String s = outFormat.format(now);  
		return s;  
	}

	public static boolean verify(String text, String sign, String key, String input_charset) {
		text = text + key;     
		String mysign =MD5.MD5Encode(text, input_charset).toUpperCase();  
		System.out.println(mysign);	System.out.println(mysign);	System.out.println(mysign);	System.out.println(mysign);
		if (mysign.equals(sign)) {     
			return true;     
		} else {     
			return false;     
		}     
	}  
}

package cn.myutils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class XMLUtil {
    public static Map doXMLParse(String strxml) throws Exception {  
           strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");  

           if(null == strxml || "".equals(strxml)) {  
               return null;  
           }  

           Map m = new HashMap();  

           InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));  
           SAXBuilder builder = new SAXBuilder();  
           Document doc = builder.build(in);  
           Element root = doc.getRootElement();  
           List list = root.getChildren();  
           Iterator it = list.iterator();  
           while(it.hasNext()) {  
               Element e = (Element) it.next();  
               String k = e.getName();  
               String v = "";  
               List children = e.getChildren();  
               if(children.isEmpty()) {  
                   v = e.getTextNormalize();  
               } else {  
                   v = XMLUtil.getChildrenText(children);  
               }  

               m.put(k, v);  
           }  

           //关闭流  
           in.close();  

           return m;  
       }  

       /** 
        * 获取子结点的xml 
        * @param children 
        * @return String 
        */  
       public static String getChildrenText(List children) {  
           StringBuffer sb = new StringBuffer();  
           if(!children.isEmpty()) {  
               Iterator it = children.iterator();  
               while(it.hasNext()) {  
                   Element e = (Element) it.next();  
                   String name = e.getName();  
                   String value = e.getTextNormalize();  
                   List list = e.getChildren();  
                   sb.append("<" + name + ">");  
                   if(!list.isEmpty()) {  
                       sb.append(XMLUtil.getChildrenText(list));  
                   }  
                   sb.append(value);  
                   sb.append("</" + name + ">");  
               }  
           }  

           return sb.toString();  
       }  
}

项目具体下载地址:点击打开链接
展开阅读全文

没有更多推荐了,返回首页