在上一节中我们学习了如何在微信服务号中配置URL和token,现在介绍一下如何开发与微信交互的Servlet。
package com.demo.weixin.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
/import com.demo.weixin.service.CoreService;
import com.demo.weixin.util.SignUtil;
/**
* 核心请求处理类
*
*
*/
public class CoreServlet extends HttpServlet {
private static final Logger logger = Logger.getLogger(CoreServlet.class);
/**
* 确认请求来自微信服务器
*/
public 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 echostr = request.getParameter("echostr");
PrintWriter out = response.getWriter();
// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
String token ="weixin";
if (SignUtil.checkSignature(token,signature, timestamp, nonce))
{
out.print(echostr);//如果签名成功,返回给微信
}
out.close();
out = null;
}
/**
* 处理微信服务器发来的消息
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// 将请求、响应的编码均设置为UTF-8(防止中文乱码)
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8") ;
//本节暂不介绍微信消息处理
//String respMessage = CoreService.processWeixinRequest(request);
//logger.info(respMessage);//输出响应的消息字符串
// 响应消息
PrintWriter out = response.getWriter();
out.print(respMessage);
out.close();
}
}
SignUtil.java的代码及servlet配置参考:
http://www.openjweb.com/portal/pubinfo/001031003/20151011/6d3d8a2b966f46178d5f8310628d1161.html
手机端浏览参考:
http://www.openjweb.com/portal/pubinfo/001031003/20151011/m_6d3d8a2b966f46178d5f8310628d1161.html
版权声明:本文为博主原创文章,未经博主允许不得转载。