JAVA微信开发weixin4j新手接入之Servlet方式接入

今天为大家来演示一下,使用Java Servlet方式,用weixin4j如何进行新手接入。

首先大家需要新建一个空的web项目。

下面是代码:

package org.weixin4j.demo; import com.thoughtworks.xstream.XStream;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.weixin4j.Configuration;import org.weixin4j.message.OutputMessage;import org.weixin4j.message.TextOutputMessage;import org.weixin4j.util.TokenUtil;import org.weixin4j.util.XStreamFactory; /** * 新手接入 * 本次接入设定的访问URL为:公众号名称 * @author weixin4j<weixin4j@ansitech.com> */public class WechatServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String path = request.getServletPath();//1.验证消息真实性//获取微信公众号String gongzonghao = path.substring(path.lastIndexOf("/"));//如果获取不到公众号,则向服务器发生错误信息if (gongzonghao == null) {response.getWriter().write("error");} else {//根据公众号,算出对应的Token,然后进行验证gongzonghao = gongzonghao.substring(1);//获取配置文件配置的TokenString token = Configuration.getProperty("weixin4j.token");if (Configuration.isDebug()) {System.out.println("取出公众号Token:" + token);}//成为开发者验证String signature = request.getParameter("signature"); // 微信加密签名String timestamp = request.getParameter("timestamp"); // 时间戳String nonce = request.getParameter("nonce");// 随机数String echostr = request.getParameter("echostr");////确认此次GET请求来自微信服务器,原样返回echostr参数内容,,则接入生效,成为开发者成功,否则接入失败if (TokenUtil.checkSignature(token, signature, timestamp, nonce)) {response.getWriter().write(echostr);} else {response.getWriter().write("error");}}}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {OutputMessage outputMsg = new TextOutputMessage("您的消息服务器已收到!");// 把发送发送对象转换为xml输出XStream xs = XStreamFactory.init(true);xs.alias("xml", outputMsg.getClass());String xml = xs.toXML(outputMsg);if (Configuration.isDebug()) {System.out.println("POST输出消息:[" + xml + "]");}response.getWriter().write(xml);}}接下来是配置web.xml:

<!– Servlet方式 微信接入配置 –><servlet><servlet-name>wechat</servlet-name><servlet-class>org.weixin4j.demo.WechatServlet</servlet-class></servlet><servlet-mapping><servlet-name>wechat</servlet-name><url-pattern>/api/*</url-pattern></servlet-mapping>

最后,将项目打包,发布到服务器,就可以在微信公众号平台中,进行开发者接入认证了。

祝你部署成功,生活愉快!

明天会有更精彩的内容,别走开,马上回来!

您可以加入我们的官方QQ群:365736353,专业人为您解答各种技术问题。

转载至:更多文章,请关注:

先知三日,富贵十年。

JAVA微信开发weixin4j新手接入之Servlet方式接入

相关文章:

你感兴趣的文章:

标签云: