1. 程式人生 > >Java後臺與微信公眾號互動----接收並處理微信客戶端傳送的請求

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);
	}
}