Java微信二次开发(二)
第二天,做微信文本消息接口请求与发送
需要导入库:dom4j-1.6.1.jar,xstream-1.3.1.jar
第一步:新建包com.wtz.message.response,新建类BaseMessage.java
package com.wtz.message.response; /**
* @author wangtianze QQ:864620012
* @date 2017年4月19日 下午3:12:40
* <p>version:1.0</p>
* <p>description:基础消息类</p>
*/
public class BaseMessage {
//接收方
private String ToUserName;
//发送方
private String FromUserName;
//消息的创建时间
private long CreateTime;
//消息类型
private String MsgType; public String getToUserName() {
return ToUserName;
}
public void setToUserName(String toUserName) {
ToUserName = toUserName;
}
public String getFromUserName() {
return FromUserName;
}
public void setFromUserName(String fromUserName) {
FromUserName = fromUserName;
}
public long getCreateTime() {
return CreateTime;
}
public void setCreateTime(long createTime) {
CreateTime = createTime;
}
public String getMsgType() {
return MsgType;
}
public void setMsgType(String msgType) {
MsgType = msgType;
}
}
第二步:找到包com.wtz.message.response,新建类TextMessage.java
package com.wtz.message.response; /**
* @author wangtianze QQ:864620012
* @date 2017年4月19日 下午3:22:33
* <p>version:1.0</p>
* <p>description:文本消息类</p>
*/
public class TextMessage extends BaseMessage{
//消息内容
private String Content; public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
}
第三步:找到包com.wtz.util,新建类MessageUtil.java
package com.wtz.util; import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader; import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.wtz.message.response.TextMessage; /**
* @author wangtianze QQ:864620012
* @date 2017年4月19日 下午3:29:58
* <p>version:1.0</p>
* <p>description:消息处理工具类</p>
*/
public class MessageUtil {
//定义了消息类型(常量:文本类型)
public static final String RESP_MESSAGE_TYPE_TEXT = "text"; //从流中解析出每个节点的内容
public static Map<String,String> parseXml(HttpServletRequest request) throws IOException{
Map<String,String> map = new HashMap<String,String>(); //从输入流中获取流对象
InputStream in = request.getInputStream(); //构建SAX阅读器对象
SAXReader reader = new SAXReader();
try {
//从流中获得文档对象
Document doc = reader.read(in); //获得根节点
Element root = doc.getRootElement(); //获取根节点下的所有子节点
List<Element> children = root.elements(); for(Element e:children){
//遍历每一个节点,并按照节点名--节点值放入map中
map.put(e.getName(), e.getText());
System.out.println("用户发送的消息XML解析为:" + e.getName() + e.getText());
} //关闭流
in.close();
in = null;
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return map;
} /**
* 用于扩展节点数据按照<ToUserName><![CDATA[toUser]]></ToUserName>,中间加了CDATA段
*/
private static XStream xstream = new XStream(new XppDriver(){
public HierarchicalStreamWriter createWriter(Writer out){
return new PrettyPrintWriter(out){
boolean cdata = true;
public void startNode(String name,Class clazz){
super.startNode(name,clazz);
} protected void writeText(QuickWriter writer,String text){
if(cdata){
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
}else{
writer.write(text);
}
}
};
}
}); /**
* 将文本消息转换成XML格式
*/
public static String messageToXml(TextMessage textMessage){
xstream.alias("xml",textMessage.getClass());
String xml = xstream.toXML(textMessage);
System.out.println("响应所转换的XML:"+xml);
return xml;
}
}
第四步:找到包com.wtz.service,新建类ProcessService.java
package com.wtz.util; import java.io.IOException;
import java.util.Date;
import java.util.Map; import javax.servlet.http.HttpServletRequest; import com.wtz.message.response.TextMessage; /**
* @author wangtianze QQ:864620012
* @date 2017年4月19日 下午8:04:14
* <p>version:1.0</p>
* <p>description:核心服务类</p>
*/
public class ProcessService {
public static String dealRequest(HttpServletRequest request) throws IOException{
//响应的XML串
String respXml = ""; //要响应的文本内容
String respContent = "未知的消息类型";
Map<String,String> requestMap = MessageUtil.parseXml(request);
String fromUserName = requestMap.get("FromUserName");
String toUserName = requestMap.get("ToUserName");
String MsgType = requestMap.get("MsgType");
String Content = requestMap.get("Content"); System.out.println("用户给公众号发的消息为:" + Content); //构建一条文本消息
TextMessage textMessage = new TextMessage();
textMessage.setToUserName(fromUserName);
textMessage.setFromUserName(toUserName);
textMessage.setCreateTime(new Date().getTime());
textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT); if(MsgType.equals(MessageUtil.RESP_MESSAGE_TYPE_TEXT)){
respContent = "王天泽的公众号收到了您的一条文本消息:" + Content + ",时间戳是:" + (new Date().getTime());
}
textMessage.setContent(respContent);
respXml = MessageUtil.messageToXml(textMessage); System.out.println("respXml:"+respXml); return respXml;
}
}
第五步:找到包com.wtz.service下的LoginServlet类,重写doPost方法
package com.wtz.service; 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 com.wtz.util.MessageUtil;
import com.wtz.util.ProcessService;
import com.wtz.util.ValidationUtil; /**
* @author wangtianze QQ:864620012
* @date 2017年4月17日 下午8:11:32
* <p>version:1.0</p>
* <p>description:微信请求验证类</p>
*/
public class LoginServlet extends HttpServlet { @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("get请求。。。。。。"); //1.获得微信签名的加密字符串
String signature = request.getParameter("signature"); //2.获得时间戳信息
String timestamp = request.getParameter("timestamp"); //3.获得随机数
String nonce = request.getParameter("nonce"); //4.获得随机字符串
String echostr = request.getParameter("echostr"); System.out.println("获得微信签名的加密字符串:"+signature);
System.out.println("获得时间戳信息:"+timestamp);
System.out.println("获得随机数:"+nonce);
System.out.println("获得随机字符串:"+echostr); PrintWriter out = response.getWriter(); //验证请求确认成功原样返回echostr参数内容,则接入生效,成为开发者成功,否则失败
if(ValidationUtil.checkSignature(signature, timestamp, nonce)){
out.print(echostr);
} out.close();
out = null;
} /**
* 接受微信服务器发过来的XML数据包(通过post请求发送过来的)
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8"); //获取微信加密的签名字符串
String signature = request.getParameter("signature"); //获取时间戳
String timestamp = request.getParameter("timestamp"); //获取随机数
String nonce = request.getParameter("nonce"); PrintWriter out = response.getWriter(); if(ValidationUtil.checkSignature(signature,timestamp,nonce)){
String respXml = "";
try {
respXml = ProcessService.dealRequest(request);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.print(respXml);
}
out.close();
out = null;
}
}
完成微信文本消息接口请求与发送。
Java微信二次开发(二)的更多相关文章
- Java微信公众平台开发(二)--微信服务器post消息体的接收
转自: http://www.cuiyongzhi.com/post/39.html 在上一篇的文章中我们详细讲述了如何将我们的应用服务器和微信腾讯服务器之间的对接操作,最后接入成功,不知道你有没有发 ...
- Java微信公众平台开发_02_启用服务器配置
源码将在晚上上传到 github 一.准备阶段 需要准备事项: 1.一个能在公网上访问的项目: 见:[ Java微信公众平台开发_01_本地服务器映射外网 ] 2.一个微信公众平台账号: 去注册: ...
- Java微信公众平台开发_07_JSSDK图片上传
一.本节要点 1.获取jsapi_ticket //2.获取getJsapiTicket的接口地址,有效期为7200秒 private static final String GET_JSAPITIC ...
- Java微信公众平台开发--番外篇,对GlobalConstants文件的补充
转自:http://www.cuiyongzhi.com/post/63.html 之前发过一个[微信开发]系列性的文章,也引来了不少朋友观看和点评交流,可能我在写文章时有所疏忽,对部分文件给出的不是 ...
- Java微信公众平台开发【番外篇】(七)--公众平台测试帐号的申请
转自:http://www.cuiyongzhi.com/post/45.html 前面几篇一直都在写一些比较基础接口的使用,在这个过程中一直使用的都是我个人微博认证的一个个人账号,原本准备这篇是写[ ...
- Java微信公众号开发梳理
Java微信公众号开发梳理 现在微信公众平台的开发已经越来越普遍,这次开发需要用到微信公众平台.因此做一个简单的记录,也算是给那些没踩过坑的童鞋一些启示吧.我将分几块来简单的描述一下,之后会做详细的说 ...
- Java微信公众平台开发(十二)--微信用户信息的获取
转自:http://www.cuiyongzhi.com/post/56.html 前面的文章有讲到微信的一系列开发文章,包括token获取.菜单创建等,在这一篇将讲述在微信公众平台开发中如何获取微信 ...
- Java微信分享接口开发
发布时间:2018-11-07 技术:springboot+maven 概述 微信JS-SDK实现自定义分享功能,分享给朋友,分享到朋友圈 详细 代码下载:http://www.demodas ...
- Java微信公众平台开发(十六)--微信网页授权(OAuth2.0授权)获取用户基本信息
转自:http://www.cuiyongzhi.com/post/78.html 好长时间没有写文章了,主要是最近的工作和生活上的事情比较多而且繁琐,其实到现在我依然还是感觉有些迷茫,最后还是决定静 ...
- Java微信公众平台开发(一)--接入微信公众平台
转自:http://www.cuiyongzhi.com/post/38.html (一)接入流程解析 在我们的开发过程中无论如何最好的参考工具当然是我们的官方文档了:http://mp.weixin ...
随机推荐
- cocoapods 报错
1.[!] ERROR: Parsing unable to continue due to parsing error: contained in the file located at xxx/x ...
- mysql show profiles 使用分析sql 性能
Show profiles是5.0.37之后添加的,要想使用此功能,要确保版本在5.0.37之后. 查看一下我的数据库版本 MySQL> Select version(); +-------- ...
- Bat 批处理杀死进程 重新启动程序
@echo offset pa=%cd%taskkill /F /IM wgscdTool.exeecho %pa%\wgscdTool.exeping /n 2 127.1>nulstart ...
- WPF编程,通过DoubleAnimation控制图片的透明度,将重叠的图片依次显示。
原文:WPF编程,通过DoubleAnimation控制图片的透明度,将重叠的图片依次显示. 版权声明:我不生产代码,我只是代码的搬运工. https://blog.csdn.net/qq_43307 ...
- 记录 第一次体验安装python第三方库的全过程
目的:安装 Pillow库 现状是:python是3.4,easy_install没有安装:pip没有安装, 步骤: 1.安装Pillow库需要安装pip 2.安装pip需要安装easy_instal ...
- Sterling B2B Integrator与SAP交互 - 01 简介
公司近期实施上线了SAP系统,由于在和客户的数据交互中采用了较多的EDI数据交换,且多数客户所采用的EDI数据并不太相同(CSV,XML,X12,WebService),所以在EDI架构上选择了IBM ...
- memcached 和redis比较
同属于NOSQL存储,网上流传很多memcached能做的是redis都可以做,为什么基本现在两种都火,原因他们有各自擅长的地方. memcahed内部采用多核模式,单列运行很快.memcached采 ...
- 2014.8.23 Research Meeting Report
Dear All: It was good talk yesterday. However, I want to emphasize that, finally it is the *work* an ...
- Nginx安装负载均衡配置 fair check扩展
前言 本文主要是针对Nginx安装.负载均衡配置,以及fair智能选举.check后端节点检查扩展功能如何扩展,进行讲解说明. fair模块: upstream-fair,“公平的”Nginx 负载均 ...
- Deferred Shading 延迟着色(翻译)
原文地址:https://en.wikipedia.org/wiki/Deferred_shading 在3D计算机图形学领域,deferred shading 是一种屏幕空间着色技术.它被称为Def ...