微信公众平台开发学习记录(3)————接收消息和发送回复消息

当普通微信用户向公众账号发消息时,微信服务器将POST消息的XML数据包到开发者填写的URL上。

当用户发送消息给公众号时(或某些特定的用户操作引发的事件推送时),会产生一个POST请求,开发者可以在响应包(Get)中返回特定XML结构,来对该消息进行响应(现支持回复文本、图片、图文、语音、视频、音乐)。严格来说,发送被动响应消息其实并不是一种接口,而是对微信服务器发过来消息的一次回复。回复消息是根据接收的xml中获取到用户信息,根据各类型消息XML结构示例进行拼接。

代码:

package com.qs.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;
import com.qs.util.SignUtil;

/**
 * @author qiaoshuai
 * @createDate 2016-3-1
 */
public class TestWeiXinAction extends ActionSupport implements
		ServletRequestAware, ServletResponseAware {

	private static final long serialVersionUID = -799327593656049028L;
	protected HttpServletRequest request;
	private HttpServletResponse response;

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public void checkSignature() throws IOException {
		boolean isGet = request.getMethod().toLowerCase().equals("get");
		if (isGet) {
			// 微信加密签名
			String signature = request.getParameter("signature");
			System.out.println("signature=" + signature);
			// 时间戳
			String timestamp = request.getParameter("timestamp");
			System.out.println("timestamp=" + timestamp);
			// 随机数
			String nonce = request.getParameter("nonce");
			System.out.println("nonce=" + nonce);
			// 随机字符串
			String echostr = request.getParameter("echostr");
			System.out.println("echostr=" + echostr);
			PrintWriter out = response.getWriter();
			// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
			if (SignUtil.checkSignature(signature, timestamp, nonce)) {
				out.print(echostr);
			}
			out.close();
			out = null;
		} else {
			// POST
			responseMsg();
		}

	}
	
	public void responseMsg() throws  IOException{
		String outString = "";
		String replyString = "";
		BufferedReader br = new BufferedReader(new InputStreamReader(
				(ServletInputStream) request.getInputStream(), "utf-8"));
		String line = null;
		StringBuilder sb = new StringBuilder();
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		String xmlS = sb.toString();
		System.out.println(xmlS);

		if (xmlS != null && !xmlS.equals("")) {
			// 用户发送者
			int fromuser_s = xmlS.indexOf("<FromUserName><![CDATA[");
			int fromuser_e = xmlS.indexOf("]]></FromUserName>");
			String fromuser = xmlS.substring(fromuser_s + 23, fromuser_e);
			System.out.println("fromuser:" + fromuser);

			// 取出目标用户
			int touser_s = xmlS.indexOf("<ToUserName><![CDATA[");
			int touser_e = xmlS.indexOf("]]></ToUserName>");
			String touser = xmlS.substring(touser_s + 21, touser_e);
			System.out.println("touser:" + touser);

			// 获取请求类型
			int msgType_s = xmlS.indexOf("<MsgType><![CDATA[");
			int msgType_e = xmlS.indexOf("]]></MsgType>");
			String msgType = xmlS.substring(msgType_s + 18, msgType_e);
			System.out.println("msgType:" + msgType);

			// 获取请求当前时间
			int createTime_s = xmlS.indexOf("<CreateTime>");
			int createTime_e = xmlS.indexOf("</CreateTime>");
			String createTime = xmlS.substring(createTime_s + 12, createTime_e);
			int createTimeInt = Integer.parseInt(createTime);
			System.out.println("createTime:" + createTimeInt);
			
			// 接收点击推事件消息
			if ("event".equals(msgType)) {
				StringBuilder outBuilder = new StringBuilder();
				int EventKey_s = xmlS.indexOf("<EventKey><![CDATA[");
				int EventKey_e = xmlS.indexOf("]]></EventKey>");
				String eventKey = xmlS.substring(EventKey_s + 19, EventKey_e);
				System.out.println("EventKey:" + eventKey);
				if (eventKey.equals("V1001_TODAY_MUSIC")) { //

					outBuilder.append("《燕归巢》");
					outString = textDemo(outBuilder.toString());
				}else if(eventKey.equals("V1001_GOOD")){
					outBuilder.append("谢谢您的赞!");
					outString = textDemo(outBuilder.toString());
				}
			}

			// 接收文本消息
			if ("text".equals(msgType)) {
				StringBuilder outBuilder = new StringBuilder();
				int content_s = xmlS.indexOf("<Content><![CDATA[");
				int content_e = xmlS.indexOf("]]></Content>");
				String content = xmlS.substring(content_s + 18, content_e);
				System.out.println("content:" + content);
				if (content.equals("天气")) { // 帮助回复(文本回复)

					outBuilder.append("今天是晴天");
					outString = textDemo(outBuilder.toString());
				}else{
					outBuilder.append(content + "啊哈");
					outString = textDemo(outBuilder.toString());
				}
				
			}

			//
			replyString = this.replyDemo(fromuser, touser, outString);
		}
		System.out.println("replyString:" + replyString);
		this.print(replyString);

	}


	// 向请求端发送返回数据
	public void print(String content) {
		try {
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().print(content);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String replyDemo(String fromuser, String touser, String content) {
		StringBuilder outString = new StringBuilder();
		// 表头
		outString.append("<xml>");
		outString.append("    <ToUserName><![CDATA[" + fromuser
				+ "]]></ToUserName>");
		outString.append("    <FromUserName><![CDATA[" + touser
				+ "]]></FromUserName>");
		outString.append("    <CreateTime>" + new Date().getTime()
				+ "</CreateTime>");
		// 表中
		outString.append(content);
		// 表尾
		outString.append("    <FuncFlag>0</FuncFlag>");
		outString.append("</xml>");
		return outString.toString();
	}


	/**
	 *文本回复 Demo
	 * 
	 * @param content
	 *            字符串内容
	 **/
	public String textDemo(String content) {
		StringBuilder textString = new StringBuilder();
		textString.append("<MsgType><![CDATA[text]]></MsgType>");
		textString.append("<Content><![CDATA[").append(content).append(
				"]]></Content>");
		return textString.toString();
	}

	/**
	 *图文回复 Demo
	 * 
	 * @param title
	 *            标题
	 * @param description
	 *            简介内容
	 * @param picUrl
	 *            图片路径
	 * @param skipUrl
	 *            链接路径
	 * 
	 **/
	public String textPicDemo(String title, String description, String picUrl,
			String skipUrl) {
		StringBuilder textPicString = new StringBuilder();
		textPicString.append("  <MsgType><![CDATA[news]]></MsgType>");
		textPicString.append("  <ArticleCount>1</ArticleCount>");
		textPicString.append("  <Articles>");
		textPicString.append("    <item>");
		textPicString.append("      <Title><![CDATA[" + title + "]]></Title> ");
		if (description != null) {
			textPicString.append("      <Description><![CDATA[" + description
					+ "]]></Description>");
		}
		textPicString
				.append("	    <PicUrl><![CDATA[" + picUrl + "]]></PicUrl>");
		textPicString.append("      <Url><![CDATA[" + skipUrl + "]]></Url>");
		textPicString.append("    </item>");
		textPicString.append("  </Articles>");
		return textPicString.toString();
	}

	/**
	 * 多张图文回复 Demo
	 * 
	 * @param articleCount
	 *            图文数量
	 * @param content
	 *            图文内容
	 **/
	public String textPicListDemosun(String[] titles, String[] descriptions,
			String[] picUrls, String[] skipUrls) {
		StringBuilder textPicString = new StringBuilder();
		textPicString.append("  <MsgType><![CDATA[news]]></MsgType>");
		textPicString.append("  <ArticleCount>" + 1 + "</ArticleCount>");
		textPicString.append("  <Articles>");
		textPicString.append("    <item>");
		textPicString.append("      <Title><![CDATA[" + titles[0]
				+ "]]></Title> ");
		if (descriptions != null) {
			textPicString.append("      <Description><![CDATA["
					+ descriptions[0] + "]]></Description>");
		}
		textPicString.append("	    <PicUrl><![CDATA[" + picUrls[0]
				+ "]]></PicUrl>");
		textPicString
				.append("      <Url><![CDATA[" + skipUrls[0] + "]]></Url>");
		textPicString.append("    </item>");
		textPicString.append("  </Articles>");
		return textPicString.toString();
	}

	/**
	 * 多张图文回复 Demo
	 * 
	 * @param articleCount
	 *            图文数量
	 * @param content
	 *            图文内容
	 **/
	public String textPicListDemo(int articleCount, String content) {
		StringBuilder textPicString = new StringBuilder();
		textPicString.append("  <MsgType><![CDATA[news]]></MsgType>");
		textPicString.append("  <ArticleCount>" + articleCount
				+ "</ArticleCount>");
		textPicString.append("  <Articles>");
		textPicString.append(content);
		textPicString.append("  </Articles>");
		return textPicString.toString();
	}


}

效果:





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值