首先,想用开放模式需要先成为开发者。成为开发者有两种写法。

  一是:通过jsp页面,用out.print("echostr")//SHA1加密的字符串;

  二是:通过Servlet。doGet返回exhostr,给微信平台。

  这里我只写第二种方式的请求(这里的请求是以get方式请求),代码如下:

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom.JDOMException;

/**
 * 微信统一入口
 * @author slz
 * 2013-7-26 上午10:17:08
 */
public class WeixinServlet extends HttpServlet {

 public WeixinServlet() {
  super();
 }

 public void destroy() {
  super.destroy();
 }

 /**
  * 微信公众平台  成为开发者验证入口
  */
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  doPost(request, response);
 }

 /**
  * 微信公众平台  所有接口入口
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
 
  response.setCharacterEncoding("UTF-8");
  request.setCharacterEncoding("UTF-8");
  PrintWriter out = response.getWriter();
  String TOKEN = "sun";//Token
  String signature = request.getParameter("signature");//SHA1加密字符串
  String timestamp = request.getParameter("timestamp");//时间
  String nonce = request.getParameter("nonce");//随机数
  String echoStr = request.getParameter("echostr");//随机字符串
  if(StrUtil.isNotNull(echoStr)){
          String[] a = {TOKEN,timestamp,nonce};
          Arrays.sort(a);//数组排序
          String str = "";
          for(int i=0;i<a.length;i++){
                  str += a[i];
          }

          String echo = new SHA1().getDigestOfString(str.getBytes());//SHA1加密

          if(echo.equals(signature)){
                  out.print(echoStr);
          }else{
                  out.print("123");
          }
  }else{
          try {
                  InputStream is = request.getInputStream();
                  PushManage push = new PushManage();
                  String getXml = push.PushManageXml(is);
                  System.out.println("getXml:"+getXml);
                  out.print(getXml);
          } catch (JDOMException e) {
                  out.print("");
          }
  }
  out.flush();
  out.close();
 }

}