com.github.xiaoyuge5201.weixin.WeiXinUtils Maven / Gradle / Ivy
package com.github.xiaoyuge5201.weixin;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author xiaoyuge
*/
public class WeiXinUtils {
private static Logger log = LoggerFactory.getLogger(WeiXinUtils.class);
/**
* key为from openid, value为我们公众号的openid
*/
public static ConcurrentHashMap openidMap = new ConcurrentHashMap();
/**
* 解析XML,获取指定属性值
* @throws DocumentException
*/
public static String getValue(String xml , String code) throws DocumentException{
Document dom = DocumentHelper.parseText(xml);
Element root=dom.getRootElement();
String return_code = root.element(code).getText();
return return_code;
}
/**
* 指定url发送xml数据
*/
public static String postXML(String uri , String xml) {
StringBuffer str = new StringBuffer();
try {
URL url = new URL(uri);
URLConnection con = url.openConnection();
con.setDoOutput(true);
con.setRequestProperty("Pragma:", "no-cache");
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestProperty("Content-Type", "text/xml");
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
out.write(new String(xml.getBytes("utf-8")));
out.flush();
out.close();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = "";
for (line = br.readLine(); line != null; line = br.readLine()) {
str.append(line);
}
} catch (MalformedURLException e) {
log.error("信息:"+e.toString(),e);
} catch (IOException e) {
log.error("信息:"+e.toString(),e);
}
return str.toString();
}
/**
* 随机字符串
*
*/
public static String getRandomString(int length) {
String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
/**
* 生成十位随机数
*/
public static String tenRandomNum(){
Random random = new Random();
StringBuffer str = new StringBuffer();
for (int i = 0; i < 10; i++) {
Integer x = random.nextInt(10);
str.append(x.toString());
}
return str.toString();
}
/**
* 生成3位随机数
* @return
*/
public static String threeRandomNum(){
Random random = new Random();
StringBuffer str = new StringBuffer();
for (int i = 0; i < 3; i++) {
Integer x = random.nextInt(10);
str.append(x.toString());
}
return str.toString();
}
}