使用JAVA开发微信公众平台接口

研究了下微信公众平台接口开发,可回复用户发来的请求

由于腾讯限制不能每天自动群发送信息

 

WeChatServlet 类:

package com.wechat.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wechat.utils.EncryptUtil;
import com.wechat.utils.XmlUtil;

public class WeChatServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	//微信平台上填的Token和这里需要一致
	public static final String Token = "loveplat";

	/**
	 * 微信公众平台验证调用方法
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String[] ArrTmp = { Token, timestamp, nonce };
		Arrays.sort(ArrTmp);
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < ArrTmp.length; i++) {
			sb.append(ArrTmp[i]);
		}
		String pwd = EncryptUtil.Encrypt(sb.toString());
		String echostr = request.getParameter("echostr");
		System.out.println("pwd=="+pwd);
		System.out.println("echostr=="+echostr);
		if(pwd.equals(signature)){
			if(!"".equals(echostr) && echostr != null){
				response.getWriter().print(echostr);
			}
		}
	}

	/**
	 * 用户向公众平台发信息并自动返回信息
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		StringBuffer sb = new StringBuffer();
		String line;
		Map<String, String> map = null;
		try {
			request.setCharacterEncoding("UTF-8");
			BufferedReader reader = request.getReader();
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			map = XmlUtil.xml2Map(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		sb = new StringBuffer();
	
		sb.append("<xml><ToUserName><![CDATA[").append(
				map.get("xml.FromUserName")).append(
				"]]></ToUserName><FromUserName><![CDATA[").append(
				map.get("xml.ToUserName")).append(
				"]]></FromUserName><CreateTime>").append(
				map.get("xml.CreateTime")).append(
				"</CreateTime><MsgType><![CDATA[text]]></MsgType>").append(
				"<Content><![CDATA[收到");
		sb.append("]]></Content>").append("<FuncFlag>0</FuncFlag></xml>");
		response.setCharacterEncoding("UTF-8");
		System.out.println(sb.toString());
		response.getWriter().print(sb.toString());
	}


	@Override
	public void destroy() {
		super.destroy();
	}

	@Override
	public void init() throws ServletException {
		super.init();
	}

}

 XmlUtil 类:需要导入jdom.jar包

package com.wechat.utils;

import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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

public class XmlUtil {

	public static Map<String, String> xml2Map(String xmlStr)
			throws JDOMException, IOException {
		Map<String, String> rtnMap = new HashMap<String, String>();
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(new StringReader(xmlStr));
		// 得到根节点
		Element root = doc.getRootElement();
		String rootName = root.getName();
		rtnMap.put("root.name", rootName);
		// 调用递归函数,得到所有最底层元素的名称和值,加入map中
		convert(root, rtnMap, rootName);
		return rtnMap;
	}

	/**
	 * 递归函数,找出最下层的节点并加入到map中,由xml2Map方法调用。
	 * 
	 * @param e
	 *           xml 节点,包括根节点
	 * @param map
	 *            目标map
	 * @param lastname
	 *            从根节点到上一级节点名称连接的字串
	 */
	public static void convert(Element e, Map<String, String> map,
			String lastname) {
		if (e.getAttributes().size() > 0) {
			Iterator it_attr = e.getAttributes().iterator();
			while (it_attr.hasNext()) {
				Attribute attribute = (Attribute) it_attr.next();
				String attrname = attribute.getName();
				String attrvalue = e.getAttributeValue(attrname);
				map.put(lastname + "." + attrname, attrvalue);
			}
		}
		List children = e.getChildren();
		Iterator it = children.iterator();
		while (it.hasNext()) {
			Element child = (Element) it.next();
			String name = lastname + "." + child.getName();
			// 如果有子节点,则递归调用
			if (child.getChildren().size() > 0) {
				convert(child, map, name);
			} else {
				// 如果没有子节点,则把值加入map
				map.put(name, child.getText());
				// 如果该节点有属性,则把所有的属性值也加入map
				if (child.getAttributes().size() > 0) {
					Iterator attr = child.getAttributes().iterator();
					while (attr.hasNext()) {
						Attribute attribute = (Attribute) attr.next();
						String attrname = attribute.getName();
						String attrvalue = child.getAttributeValue(attrname);
						map.put(name + "." + attrname, attrvalue);
					}
				}
			}
		}
	}

}

 

EncryptUtil类:

package com.wechat.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class EncryptUtil {

	public static String Encrypt(String strSrc) {
		MessageDigest md = null;
		String strDes = null;

		byte[] bt = strSrc.getBytes();
		try {
			md = MessageDigest.getInstance("SHA-1");
			md.update(bt);
			strDes = bytes2Hex(md.digest()); //to HexString
		} catch (NoSuchAlgorithmException e) {
			System.out.println("Invalid algorithm.");
			return null;
		}
		return strDes;
	}

	public static String bytes2Hex(byte[] bts) {
		String des = "";
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				des += "0";
			}
			des += tmp;
		}
		return des;
	}
	
}

 

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>WeChatServlet</servlet-name>
    <servlet-class>com.wechat.servlet.WeChatServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>WeChatServlet</servlet-name>
    <url-pattern>/WeChatServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  
</web-app>

 

测试案例:

大家可关注微信公众账号:在线匹配交友

微信里面暂时搜索不到,大家可扫描二维码关注,二维码见附件

做了个最简单的回复信息,由于获取不到用户信息还没有想到好的想法

欢迎大家提供宝贵意见

暂时是本机做服务器的如果服务没开可能不会收到自动回复信息

posted @ 2013-04-18 18:09  栈长  阅读(275)  评论(0编辑  收藏  举报