微信公共平台(二)自动回复消息

package com.chaowen;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.Writer;
import java.net.MalformedURLException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Date;
import java.util.Scanner;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import com.chaowen.bean.WeChatReqBean;
import com.chaowen.bean.WeChatRespBean;
import com.chaowen.common.Constants;
import com.sun.xml.bind.marshaller.CharacterEscapeHandler;

/**
 * Servlet implementation class WeiXinServlet
 */
public class WeiXinServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static final String Token = "token";   



	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8"); 
		PrintWriter   out   =   response.getWriter();

		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 = 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);
			}
		}
		
		out.flush();
		out.close();
		//this.doPost(request, response);
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 Scanner scanner = new Scanner(request.getInputStream());
         response.setContentType("application/xml");
         response.setCharacterEncoding("UTF-8"); 
         PrintWriter out = response.getWriter();
         try {
        	// 1、获取用户发送的信息
        	
        	 InputStream is = request.getInputStream();
         	// 取HTTP请求流长度
              int size = request.getContentLength();
              // 用于缓存每次读取的数据
              byte[] buffer = new byte[size];
              // 用于存放结果的数组
              byte[] xmldataByte = new byte[size];
              int count = 0;
              int rbyte = 0;
              // 循环读取
              while (count < size) { 
                  // 每次实际读取长度存于rbyte中
                  rbyte = is.read(buffer); 
                  for(int i=0;i<rbyte;i++) {
                      xmldataByte[count + i] = buffer[i];
                  }
                  count += rbyte;
              }
              is.close();
              String requestStr = new String(xmldataByte, "UTF-8");
        	
        	
        	 // 2、解析用户的信息
        	 JAXBContext jc = JAXBContext.newInstance(WeChatReqBean.class);
        	 Unmarshaller u = jc.createUnmarshaller();
        	 WeChatReqBean reqBean = (WeChatReqBean) u.unmarshal(new StringReader(requestStr));
        	 
        	// 3、判定用户了解动作
        	 String content = getContent(reqBean);
        	// 4、创建一个回复消息
        	 jc = JAXBContext.newInstance(WeChatRespBean.class);
        	 Marshaller m = jc.createMarshaller();
        	 m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        	 m.setProperty(CharacterEscapeHandler.class.getName(), new CharacterEscapeHandler() {
        		 @Override
        		 public void escape(char[] arg0, int arg1, int arg2, boolean arg3,
        				 Writer arg4) throws IOException {
        			 arg4.write(arg0, arg1, arg2);
        		 }
        	 });
        	 m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        	 WeChatRespBean respBean = createRespBean(reqBean, content);
        	 m.marshal(respBean, out);
        	 out.flush();


		}catch (JAXBException e) {
           e.printStackTrace();
        } finally {
            if (scanner != null) {
                scanner.close();
                scanner = null;
            }
            if (out != null) {
                out.close();
                out = null;
            }
        }
	}

	/**
	 * @param reqBean
	 * @param content
	 * @return
	 */
	private WeChatRespBean createRespBean(WeChatReqBean reqBean, String content) {
		WeChatRespBean respBean = new WeChatRespBean();
		respBean.setFromUserName(reqBean.getToUserName());
		respBean.setToUserName(reqBean.getFromUserName());
		respBean.setMsgType("text");
		respBean.setCreateTime(new Date().getTime());
		respBean.setContent(content);
		return respBean;
	}
	
	public 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 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;
	}
	
	/**
	 * @param reqBean
	 * @throws JAXBException
	 * @throws MalformedURLException
	 */
	private String getContent(WeChatReqBean reqBean) throws JAXBException, MalformedURLException {
		StringBuffer content = new StringBuffer("");
		
		switch (Constants.getType(reqBean.getMsgType())){
		case text:
			if (reqBean.getContent().contains("成长档案")) {
				// 这是新用户关注时默认发的一条信息。可以做一个欢迎处理。
				content.append("这是成长档案的介绍!"+"\r\n");
				content.append(""+"\r\n");
				content.append(""+"\r\n");
				content.append("回复h获取更多内容!"+"\r\n");
			}else if(reqBean.getContent().contains("h")){
				content.append("这是帮助信息!"+"\r\n");
				content.append("如果你还有疑问或建议:请以#开头发送文字内容,我们的客服收到留言后会尽快跟你联系。"+"\r\n");
			}else if(reqBean.getContent().contains("cp")){
				content.append("产品介绍:"+"\r\n");
				content.append("001.家园共育平台"+"\r\n");
				content.append("002.运营分析系统"+"\r\n");
				content.append("003.互动学堂"+"\r\n");
				content.append(""+"\r\n");
				content.append(""+"\r\n");
				content.append("回复数字获取更多内容!"+"\r\n");
			}
			
			else {
				content.append("你的信息已收到,我们会第一时间处理.");
			}
			break;
		case event:
			if("subscribe".equals(reqBean.getEvent())){
				// 这是新用户关注时默认发的一条信息。可以做一个欢迎处理。
				content.append("非常感谢你的添加,我们定时为你提供最新的儿童内容服务哟!"+"\r\n");
				content.append("1.想了解我们的产品请直接将产品名称回复给我(如\"成长档案\")"+"\r\n");
				content.append("2.想知道已经上线了哪些产品请回复\"cp\"或直接点击链接www.yey.com进行查看"+"\r\n");
			    content.append("3.如需帮助或了解请回复\"h\"。"+"\r\n");
			}
			break;
		case image:
			
			break;
		default:
			content.append("这是一个测试!!!");
			break;
		}
		return content.toString();
	}
}

  

原文地址:https://www.cnblogs.com/andgoo/p/3045297.html