Java后台与微信公众号交互----接收并处理微信客户端发送的请求

还是一样,理论就不说了,直接上代码!
在进行这个操作之前,必须得与微信客户端进行比对成功才行,具体可参考上一篇博客。
doGet()是上一篇博客已经说了的,在这里就不详细说了。

public class WeChatServlet extends HttpServlet {

	/**
	 * 接收微信服务器发送的4个参数并返回echostr
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("进入...");
		// 接收微信服务器以Get请求发送的4个参数
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");

		PrintWriter out = response.getWriter();
		if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
			out.print(echostr); // 校验通过,原样返回echostr参数内容
		}
	}

	/**
	 * 接收并处理微信客户端发送的请求
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		System.out.println("进入。。。");
		//设置utf-8
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/xml;charset=utf-8");

		WeiXinService weiXinService = new WeiXinService ();

		PrintWriter out = response.getWriter();
		try {
			// 拿到微信客户端发来的请求并通过工具类解析为map格式
			Map<String, String> map = Message.xmlToMap(request);
			String toUserName = map.get("ToUserName");
			String fromUserName = map.get("FromUserName");
			String msgType = map.get("MsgType");
			String content = map.get("Content");
			// String openid = map.get("openid");

			TextMeaasge text = new TextMeaasge();
			// 将信息封装到实体类中
			text.setFromUserName(toUserName); // 发送和回复是反向的
			text.setToUserName(fromUserName);
			text.setCreateTime(new Date().getTime());
			if (msgType.equals("text") || msgType.equals("image") || msgType.equals("voice") ||
					msgType.equals("video") || msgType.equals("shortvideo") || msgType.equals("location") ||
					msgType.equals("link")) {
				// 对文字、图片、语音、视频、短视频等一系列信息进行统一回复
				System.out.println(content.toCharArray());
				// 设置回复的消息内容
				text.setContent("您发送的信息是:" + content);
				// 设置消息的响应类型
				text.setMsgType("text");
			} else if (msgType.equals("event")) {
				// 对事件消息进行处理
				// 获取到事件类型
				String event = map.get("Event");
				// 获取事件的key
				String eventKey = map.get("EventKey");
				if (event.equals("subscribe")) {
					// 关注事件
					text.setContent("欢迎关注![愉快]\n");
					// 设置消息的响应类型
					text.setMsgType("text");
				} else if (event.equals("CLICK")) {
					// 点击事件
					
					// 在此进行点击事件处理
					//。。。。。。。。//
					// 处理点击事件结束
					
					// 设置消息的响应类型
					text.setMsgType("text");
					// 设置回复的消息内容
					text.setContent("点击事件。。");
				} else {
					System.out.println("关注和点击事件之外。。");
				}
			} else {
				System.out.println("发送消息和事件之外。。");
			}
			String message = null;
			// 将实体类通过工具类转换为xml
			message = Message.textMessageToXML(text);
			System.out.println(message);
			out.print(message); // 将回应发送给微信服务器
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			out.close();
		}
	}
}

消息实体类:

/**
 * 消息实体类
 * 
 * @author win7
 * 
 */
public class TextMeaasge {

	private String ToUserName;
	private String FromUserName;
	private long CreateTime;
	private String MsgType;
	private String Content;
	private String MsgId;
	
	// get、set已省略
}

实现消息的格式转换工具类,前提是导入两个jar包,dom4jxstream
dom4j下载地址:http://central.maven.org/maven2/dom4j/dom4j/1.6.1/dom4j-1.6.1.jar
xstream下载地址:http://central.maven.org/maven2/com/thoughtworks/xstream/xstream/1.4.2/xstream-1.4.2.jar
注意,xstream的jar包有很多依赖,这个可以到这里去看:https://mvnrepository.com/artifact/com.thoughtworks.xstream/xstream/1.4.2


/**
 * 实现消息的格式转换(Map类型和XML的互转)
 */
public class Message {
	/**
	 * 将XML转换成Map集合
	 */
	public static Map<String, String> xmlToMap(HttpServletRequest request)
			throws IOException, DocumentException {

		Map<String, String> map = new HashMap<String, String>();
		SAXReader reader = new SAXReader(); // 使用dom4j解析xml
		InputStream is= request.getInputStream(); // 从request中获取输入流
		Document doc = reader.read(is);

		Element root = doc.getRootElement(); // 获取根元素
		List<Element> list = root.elements(); // 获取所有节点

		for (Element e : list) {
			map.put(e.getName(), e.getText());
			System.out.println(e.getName() + "--->" + e.getText());
		}
		is.close();
		return map;
	}

	/**
	 * 将文本消息对象转换成XML
	 */
	public static String textMessageToXML(TextMeaasge textMessage) {
		System.out.println("进入textMessageToXML");
		System.out.println(textMessage.getMsgType());
		System.out.println(textMessage.getContent());
		XStream xstream = new XStream(); // 使用XStream将实体类的实例转换成xml格式
		System.out.println(",,,,,,,,,,");
		xstream.alias("xml", textMessage.getClass()); // 将xml的默认根节点替换成“xml”
		System.out.println("......");
		return xstream.toXML(textMessage);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_37253891/article/details/85048395