回复消息

根据发送的消息的xml数据包中的MsgType的类型,分别处理对应的消息

  • 在WeixinServlet的dopost方法中的处理消息和事件推送后接着输入
1
2
3
4
5
6
String respXml = WxService.getResponse(requestMap);
System.out.println(respXml);
PrintWriter out = response.getWriter();
out.print(respXml);
out.flush();
out.close();
  • 在WxService里加入用于处理所有事件和消息的回复的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public static String getResponse(Map<String,String> requestMap){
BaseMessage msg = null;
String msgType = requestMap.get("MsgType");
switch (msgType){
case "text":
msg = dealTestMessage(requestMap);
break;
case "image":
msg = dealImageMessage(requestMap);
break;
case "voice":

break;
case "video":

break;
case "shortvideo":

break;
case "location":

break;
case "link":

break;
case "event":
msg = dealEvent(requestMap);
break;
default:
break;
}
if(msg != null) {
//把消息对象处理为xml数据包
return beanToXml(msg);
}
return null;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private static BaseMessage dealTextMessage(Map<String,String> requestMap){
//用户发来的消息
String msg = requestMap.get("Content");
if(msg.equals("图文")){
List<Article> articles = new ArrayList<>();
articles.add(new Article("这是图文消息的标题","这是图文消息的详细的介绍","https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1575645124939&di=394383e3fc4a237e4a22434e90848360&imgtype=0&src=http%3A%2F%2Fimg2.100bt.com%2Fupload%2Fttq%2F20131124%2F1385272062997_middle.jpg","http://raoweijiapng.github.io"));
NewsMessage nm = new NewsMessage(requestMap,articles);
return nm;
}

//调用方法返回聊天的
String resp = chat(msg);
//System.out.println(resp);
TextMessage tm = new TextMessage(requestMap,resp);
return tm;
}

机器人聊天

1
2
3
4
private static String chat(String msg){
String rebortmsg = RebortUtil.rebortChat(msg);
return rebortmsg;
}
  • 创建com.webchat.util目录,然后创建图灵机器人的接入类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
 	package com.webchat.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
public class RebortUtil {
public static String rebortChat(String msg){
String APIKEY = "171905428dc74092b3bb1ccff8b06faa"; //图灵机器人的apikey
HttpURLConnection connection = null;
BufferedReader reader = null;
StringBuffer sb = null;
try {
String INFO = URLEncoder.encode(msg,"utf-8");
String getURL = "http://www.tuling123.com/openapi/api?key=" + APIKEY + "&info=" + INFO;
URL getUrl = new URL(getURL);
connection = (HttpURLConnection) getUrl.openConnection();
connection.connect();
// 取得输入流,并使用Reader读取
reader = new BufferedReader(new InputStreamReader( connection.getInputStream(), "utf-8"));
sb = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
// 断开连接
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}

Map mapTypes = JSON.parseObject(sb.toString());
String rebortMsg = ((JSONObject) mapTypes).getString("text");
return rebortMsg;
}
}
  • 把消息对象处理为xml数据包
1
2
3
4
5
6
7
8
9
10
11
12
13
14
private static String beanToXml(BaseMessage msg){
//System.out.println(msg);
//调用XStream把对象转换成xml文件
XStream stream = new XStream();
//设置需要处理@XStreamAlias("xml")的类
stream.processAnnotations(TextMessage.class);
stream.processAnnotations(ImageMessage.class);
stream.processAnnotations(MusicMessage.class);
stream.processAnnotations(VideoMessage.class);
stream.processAnnotations(VoiceMessage.class);
stream.processAnnotations(NewsMessage.class);
String xml = stream.toXML(msg);
return xml;
}

token的获取和处理

  • 在WxService里加入用于得到token的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
private static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
private static final String APPID = "wxe6774713a448fb6f";
private static final String APPSECRET = "1fec63da4f2a53c3224e6adf6dd4876e";
//用于存储token
private static Token tok;
//获取token
private static void getToken(){
String url = GET_TOKEN_URL.replace("APPID",APPID).replace("APPSECRET",APPSECRET);
String tokenStr = GetAndPost.get(url);
System.out.println(tokenStr);
JSONObject jsonObject = JSONObject.fromObject(tokenStr);
String token = jsonObject.getString("access_token");
String expireIn = jsonObject.getString("expires_in");
tok = new Token(token,expireIn);
}

//向外暴露的获取token
public static String getOutToken(){
if(tok == null || tok.isExpired()){
getToken();
}
return tok.getAccessToken();
}
  • 在com.webchat.util目录下创建GetAndPost类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
 	package com.webchat.util;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
public class GetAndPost {
//从指定url接收get请求
public static String get(String url){
try {
URL urlObj = new URL(url);
//开连接
URLConnection connection = urlObj.openConnection();
InputStream is = connection.getInputStream();
byte[] b = new byte[1024];
int len;
StringBuffer sb = new StringBuffer();
while ((len=is.read(b)) != -1){
sb.append(new String(b,0,len));
}

return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

//向指定url发送post请求
public static String post(String url,String data){
try {
URL urlObj = new URL(url);
//开连接
URLConnection connection = urlObj.openConnection();
//要发送数据出去,必须设置为可发送数据状态
connection.setDoOutput(true);
//获取输出流
OutputStream os = connection.getOutputStream();
//写入数据
os.write(data.getBytes());
os.close();
//获取输入流
InputStream is = connection.getInputStream();
byte[] b = new byte[1024];
int len;
StringBuffer sb = new StringBuffer();
while ((len=is.read(b)) != -1){
sb.append(new String(b,0,len));
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
  • 在com.webchat.entity目录下创建token实体类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
   package com.webchat.entity;
public class Token {
private String accessToken;
private Long expireTime;

public String getAccessToken() {
return accessToken;
}

public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}

public Long getExpireTime() {
return expireTime;
}

public void setExpireTime(Long expireTime) {
this.expireTime = expireTime;
}

public Token(String accessToken, String expireIn) {
super();
this.accessToken = accessToken;
expireTime = System.currentTimeMillis()+Integer.parseInt(expireIn)*1000;
}

//判断token是否过期
public boolean isExpired(){
return System.currentTimeMillis()>expireTime;
}
}

菜单类的封装

  • 创建com.webchat.entity.button目录,并在此目录下创建Button类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.webchat.entity.button;

import java.util.ArrayList;
import java.util.List;

public class Button {
private List<AbstractBut> button = new ArrayList<>();

public List<AbstractBut> getButton() {
return button;
}

public void setButton(List<AbstractBut> button) {
this.button = button;
}

public Button() {
}
}
  • 在com.webchat.entity.button目录下创建AbstractBut类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 	package com.webchat.entity.button;
public abstract class AbstractBut {
private String name;
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public AbstractBut(String name) {
this.name = name;
}
}
  • 在com.webchat.entity.button目录下创建继承AbstractBut类的ClickBut类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
   package com.webchat.entity.button;
public class ClickBut extends AbstractBut {

private String type = "click";
private String key;

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public String getKey() {
return key;
}

public void setKey(String key) {
this.key = key;
}

public ClickBut(String name,String key) {
super(name);
this.key = key;
}
}
  • 在com.webchat.entity.button目录下创建继承AbstractBut类的ViewBut类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
   package com.webchat.entity.button;
public class ViewBut extends AbstractBut {

private String type = "view";
private String url;

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

public ViewBut(String name, String url) {
super(name);
this.url = url;
}
}
  • 在com.webchat.entity.button目录下创建继承AbstractBut类的PhotoOrAlbumBut类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
 	package com.webchat.entity.button;
import java.util.ArrayList;
import java.util.List;
public class PhotoOrAlbumBut extends AbstractBut {
private String type = "pic_photo_or_album";
private String key;
private List<AbstractBut> sub_button = new ArrayList<>();

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public String getKey() {
return key;
}

public void setKey(String key) {
this.key = key;
}

public List<AbstractBut> getSub_button() {
return sub_button;
}

public void setSub_button(List<AbstractBut> sub_button) {
this.sub_button = sub_button;
}

public PhotoOrAlbumBut(String name,String key) {
super(name);
this.key = key;
}
}
  • 在com.webchat.entity.button目录下创建继承AbstractBut类的SubButton类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 	package com.webchat.entity.button;
import java.util.ArrayList;
import java.util.List;
public class SubButton extends AbstractBut {
private List<AbstractBut> sub_button = new ArrayList<>();
public List<AbstractBut> getSub_button() {
return sub_button;
}

public void setSub_button(List<AbstractBut> sub_button) {
this.sub_button = sub_button;
}

public SubButton(String name) {
super(name);
}
}