当前位置: 移动技术网 > IT编程>开发语言>Java > Java开发微信公众号接收和被动回复普通消息

Java开发微信公众号接收和被动回复普通消息

2019年07月22日  | 移动技术网IT编程  | 我要评论

上篇说完了如何接入微信公众号,本文说一下微信公众号的最基本功能:普通消息的接收和回复。说到普通消息,那么什么是微信公众号所定义的普通消息呢,微信开发者文档中提到的接收的普通消息包括如下几类

1.文本消息
2.图片消息
3.语音消息
4.视频消息
5.小视频消息
6.地理位置消息
7.链接消息(被动回复的消息)

被动回复的普通消息包括:

1.回复文本消息
2.回复图片消息
3.回复语音消息
4.回复视频消息
5.回复音乐消息
6.回复图文消息

其实接收消息和被动回复消息这两个动作是不分家的,这本来就是一个交互场景,一般情况就是公众号通过分析接收到的消息,会给出对应的回复。当然也不能排除一些特殊业务了。

如何接收消息

要接收的这7中消息的xml格式这里就不列出了,请到官方文档查看,有具体的格式定义和属性说明。格式很简单,基本共有属性包括tousername、fromusername、createtime、msgtype、msgid,并且每种类型有自己特殊的属性。

看到这里,其实就很明白了,接收消息的过程其实就是获取post请求的这个xml,然后对这个xml进行分析的过程。post请求的入口还是之前提到的微信公众号接入的那个地址,整个公众号的所有请求都会走这个入口,只是接入时是get请求,其它情况下是post请求。处理xml这里用了dom4j,xml处理代码如下,在servlet的post方法中调用parsexml方法即可:

public static map parsexml(httpservletrequest request) throws exception {
// 将解析结果存储在hashmap中
map map = new hashmap();
// 从request中取得输入流
inputstream inputstream = request.getinputstream();
/*
* 读取request的body内容 此方法会导致流读取问题 premature end of file. nested exception:
* premature end of file string requestbody =
* inputstream2string(inputstream); system.out.println(requestbody);
*/
// 读取输入流
saxreader reader = new saxreader();
document document = reader.read(inputstream);
// 得到xml根元素
element root = document.getrootelement();
// 得到根元素的所有子节点
list<element> elementlist = root.elements();
// 遍历所有子节点
for (element e : elementlist)
map.put(e.getname(), e.gettext());
// 释放资源
inputstream.close();
inputstream = null;
return map;
}
private static string inputstream2string(inputstream is) throws ioexception {
bytearrayoutputstream baos = new bytearrayoutputstream();
int i = -1;
while ((i = is.read()) != -1) {
baos.write(i);
}
return baos.tostring();
}

如何被动回复消息

下面我基于这样一个逻辑来演示构造回复的消息,接收到文本消息"文本",回复文本消息;接收到“图片”,回复图片消息;接收到“语音”,回复语音消息;接收到“视频”,回复视频消息;接收到“音乐”,回复音乐消息;接收到“图文”,回复图文消息。

以回复文本消息作为说明:

<xml>
<tousername><![cdata[发消息的人,即订阅者]]></tousername>
<fromusername><![cdata[微信公众号本身]]></fromusername>
<createtime>消息创建时间(整形)</createtime>
<msgtype><![cdata[text]]></msgtype>
<content><![cdata[消息内容]]></content>
</xml>

前两个属性可以从接收的消息中获取,接收的消息格式如下:

<xml>
<tousername><![cdata[touser]]></tousername>
<fromusername><![cdata[fromuser]]></fromusername> 
<createtime>1348831860</createtime>
<msgtype><![cdata[text]]></msgtype>
<content><![cdata[this is a text]]></content>
<msgid>1234567890123456</msgid>
</xml> 

其中接收消息格式中的tousername便是回复消息的fromusername,接收消息格式中的fromusername便是回复消息的tousername。

createtime为消息发送的时间戳。msgtype为消息类型,文本为text。content为消息内容。

具体每一种类型消息的回复,就是构造此种类型的xml格式内容,格式大同小异,只是音乐、视频、语音、图文格式相对于文本消息构造的xml内容稍微复杂一点。具体可参考官方文档。这里不做赘述,相信各位一看便明白。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网