验证中...
开源中国 2018 年度最后一场技术盛会邀你来约~错过就要等明年啦!点此立即预约
语言: Java
分类: 微信开发
最后更新于 2018-12-09 10:36
片段 1 片段 2 片段 3
JoinChatServlet1.java
原始数据 复制代码
package com.eastrobot.robotdev.wechat;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.eastrobot.robotdev.Constants;
import com.eastrobot.robotdev.util.HttpUtils;
import com.eastrobot.robotdev.wechat.entity.AccessToken;
import com.eastrobot.robotdev.wechat.util.MessageUtils;
import com.eastrobot.robotdev.wechat.util.SHA1Utils;
import com.eastrobot.robotdev.wechat.util.WechatUtils;
/**
* 接入微信公众号平台的接口
*
* @author han.sun
*
*/
public class JoinChatServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Logger log = LoggerFactory.getLogger(JoinChatServlet.class);
// private static ReceiveXmlUtils receiveXmlUtils;
// 微信上填写的Token数据
private static String Token = "sunhan";
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding(Constants.CHARSET);
response.setCharacterEncoding(Constants.CHARSET);
log.debug("GEt请求成功");
// 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
String signature = request.getParameter("signature");
// 时间戳
String timestamp = request.getParameter("timestamp");
// 随机数
String nonce = request.getParameter("nonce");
// 随机字符串
String echostr = request.getParameter("echostr");
List<String> params = new ArrayList<String>();
params.add(Token);
params.add(timestamp);
params.add(nonce);
// 1. 将token、timestamp、nonce三个参数进行字典排序
Collections.sort(params, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
// 2. 将三个参数拼接成一个字符串进行SHA1进行加密
String temp = SHA1Utils.encode(params.get(0) + params.get(1)
+ params.get(2));
// 3. 加密后的字符串与signature比较,标识该请求是来自微信
if (temp.equals(signature)) {
// 原样返回echostr参数内容,则接入成功
response.getWriter().write(echostr);
log.debug("echostr传回微信后台成功...");
} else {
log.debug("echostr传回微信后台失败...");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding(Constants.CHARSET);
response.setCharacterEncoding(Constants.CHARSET);
PrintWriter out = response.getWriter();
String result = null;
Map<String, String> map = null;
try {
map = MessageUtils.xmlToMap(request);
} catch (DocumentException e1) {
e1.printStackTrace();
}
String toUserName = map.get("ToUserName");
String fromUserName = map.get("FromUserName");
String msgType = map.get("MsgType");
String content = map.get("Content");
String echostr = request.getParameter("echostr");
// 判断是否是微信接入激活验证,只有首次接入验证时才会收到echostr参数,此时需要把它直接返回
if (echostr != null && echostr.length() > 1) {
result = echostr;
} else {
// 判断请求是是否是文本类型 text
if (MessageUtils.MESSAGE_TEXT.equals(msgType)) {
if ("文艺".equals(content)) {
result = imageProcess(toUserName, fromUserName);
// String mediaId =
// "7u19uWKlh-Nfpm8dAEpkhgxr0u5y0H5hxARQKsqtv3FjcMOV9dtFGxpYU4RvaV4t";
// result = MessageUtils.initImageMessage(mediaId,
// toUserName,fromUserName);
} else if ("图文".equals(content)) {
result = MessageUtils.initArticlesMessage(toUserName,
fromUserName);
} else {
String api = "http://ctr.demo.xiaoi.com/robot/ask.action?";
try {
URLEncoder.encode(content, Constants.CHARSET);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 拼接url
StringBuffer bf = new StringBuffer();
bf.append("question=");
bf.append(content);
bf.append("&paltform=weixin");
String url = api + bf.toString();
String message = HttpUtils.get(url, Constants.CHARSET);
message = message.substring(
message.indexOf("<Content>") + 9,
message.indexOf("</Content>"));
result = MessageUtils.initTextMessage(message, toUserName,
fromUserName);
}
}
}
out.write(result);
out.close();
}
private String imageProcess(String toUserName, String fromUserName) {
String message = null;
AccessToken token = WechatUtils.getAccessToken();
String mediaId = null;
Random ran = new Random();
int i = ran.nextInt(28);
String filePath = "/app/ibot-odin-robot-8005/webapps/robot-dev/image/0" + (i+1) + ".jpg";
try {
mediaId = WechatUtils.upload(filePath, token.getToken(),
MessageUtils.MESSAGE_IMAGE);
// mediaId =
// "7u19uWKlh-Nfpm8dAEpkhgxr0u5y0H5hxARQKsqtv3FjcMOV9dtFGxpYU4RvaV4t";
} catch (Exception e) {
e.printStackTrace();
}
message = MessageUtils.initImageMessage(mediaId, toUserName,
fromUserName);
return message;
}
}
MessageUtils.java
原始数据 复制代码
package com.eastrobot.robotdev.wechat.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
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.eastrobot.robotdev.wechat.entity.ArticlesItem;
import com.eastrobot.robotdev.wechat.entity.ArticlesMessage;
import com.eastrobot.robotdev.wechat.entity.Image;
import com.eastrobot.robotdev.wechat.entity.ImageMessage;
import com.eastrobot.robotdev.wechat.entity.TextMessage;
import com.thoughtworks.xstream.XStream;
/**
* 处理Xml消息工具类
* @author han.sun
*
*/
public class MessageUtils {
public static final String MESSAGE_SCAN = "SCAN";// 未关注公众号扫描二维码
public static final String MESSAGE_TEXT = "text";// 文本
public static final String MESSAGE_IMAGE = "image";// 图片
public static final String MESSAGE_VOICE = "voice";// 语音
public static final String MESSAGE_VIDEO = "video";// 视频
public static final String MESSAGE_LINK = "link";// 连接
public static final String MESSAGE_LOCATION = "location";// 地理位置事件
public static final String MESSAGE_EVENT = "event";// 事件
public static final String MESSAGE_SUBSCRIBE = "subscribe";// 关注
public static final String MESSAGE_UNSUBSCRIBE = "unsubscribe";// 取消关注
public static final String MESSAGE_CLICK = "CLICK";// 点击
public static final String MESSAGE_VIEW = "VIEW";// t跳转链接url
public static final String MESSAGE_NEWS = "news";
private MessageUtils() {
}
/**
* 将接受到的xml转换成Map集合
* @param request
* @return Map集合
*/
public static Map<String, String> xmlToMap(HttpServletRequest request)
throws IOException, DocumentException {
Map<String, String> map = new HashMap<String, String>();
SAXReader reader = new SAXReader();
InputStream in = request.getInputStream();
Document document = reader.read(in);
Element root = document.getRootElement();
@SuppressWarnings("unchecked")
List<Element> list = root.elements();
for (Element e : list) {
map.put(e.getName(), e.getText());
}
in.close();
return map;
}
/**
* 将文本信息转换成Xml
* @param textMessage 文本消息实体
* @return 准备返回的xml字符串
*/
private static String textMessageToXml(TextMessage textMessage) {
XStream stream = new XStream();
stream.alias("xml", textMessage.getClass());
return stream.toXML(textMessage);
}
/**
* 将图片消息转换成xml
* @param imageMessage 图片消息实体
* @return 准备返回的xml字符串
*/
private static String imageMessageToXml(ImageMessage imageMessage) {
XStream stream = new XStream();
stream.alias("xml", imageMessage.getClass());
return stream.toXML(imageMessage);
}
/**
* 图文消息转为xml
* @param newsMessage
* @return
*/
public static String articlesMessageToXml(ArticlesMessage articlesMessage){
XStream xstream = new XStream();
xstream.alias("xml", articlesMessage.getClass());
xstream.alias("item", new ArticlesItem().getClass());
return xstream.toXML(articlesMessage);
}
/**
* 图文消息的组装(类型为news)
* @param toUserName
* @param fromUserName
* @return
*/
public static String initArticlesMessage(String toUserName,String fromUserName){
String message = null;
List<ArticlesItem> newsList = new ArrayList<ArticlesItem>();
ArticlesMessage newsMessage = new ArticlesMessage();
ArticlesItem article = new ArticlesItem();
article.setTitle("图文消息");
article.setDescription("你,在或者不在;这些年风里,雨里;无论,快乐还是哀愁;我都将终点,等你 。");
article.setPicUrl("http://ctr.demo.xiaoi.com/robot-dev/image/028.jpg");
article.setUrl("https://www.baidu.com");
newsList.add(article);
newsMessage.setToUserName(fromUserName);
newsMessage.setFromUserName(toUserName);
newsMessage.setCreateTime(new Date().getTime());
newsMessage.setMsgType(MESSAGE_NEWS);
newsMessage.setArticles(newsList);
newsMessage.setArticleCount(newsList.size());
message = articlesMessageToXml(newsMessage);
return message;
}
/**
* 文本消息的组装
* @param content
* @param toUserName
* @param fromUserName
* @return 发送给客户端
*/
public static String initTextMessage(String content, String toUserName,
String fromUserName) {
String message = null;
TextMessage textMessage = new TextMessage();
textMessage.setContent(content);
textMessage.setCreateTime(new Date().getTime());
textMessage.setFromUserName(toUserName);
textMessage.setToUserName(fromUserName);
textMessage.setMsgType(MESSAGE_TEXT);
message = textMessageToXml(textMessage);
return message;
}
/**
* 图片消息的组装
* @param mediaId
* @param toUserName
* @param fromUsername
* @return 发送给客户端
*/
public static String initImageMessage(String mediaId, String toUserName,
String fromUserName) {
String message = null;
ImageMessage imageMessage = new ImageMessage();
Image image = new Image();
image.setMediaId(mediaId);
imageMessage.setImage(image);
imageMessage.setFromUserName(toUserName);
imageMessage.setToUserName(fromUserName);
imageMessage.setCreateTime(new Date().getTime());
imageMessage.setMsgType(MESSAGE_IMAGE);
message = imageMessageToXml(imageMessage);
return message;
}
public static String initMuenMessage() {
StringBuffer bf = new StringBuffer();
bf.append("你,在或者不在\n");
bf.append("这些年风里,雨里\n");
bf.append("无论是快乐,哀愁\n");
bf.append("我都将终点,等你\n");
return bf.toString();
}
}
JoinChatServlet.java
原始数据 复制代码
package com.eastrobot.robotdev.wechat;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.eastrobot.robotdev.Constants;
import com.eastrobot.robotdev.util.HttpUtils;
import com.eastrobot.robotdev.wechat.entity.AccessToken;
import com.eastrobot.robotdev.wechat.util.MessageUtils;
import com.eastrobot.robotdev.wechat.util.SHA1Utils;
import com.eastrobot.robotdev.wechat.util.WechatUtils;
/**
* 接入微信公众号平台的接口
*
* @author han.sun
*
*/
public class JoinChatServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Logger log = LoggerFactory.getLogger(JoinChatServlet.class);
// private static ReceiveXmlUtils receiveXmlUtils;
// 微信上填写的Token数据
private static String Token = "sunhan";
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding(Constants.CHARSET);
response.setCharacterEncoding(Constants.CHARSET);
log.debug("GEt请求成功");
// 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
String signature = request.getParameter("signature");
// 时间戳
String timestamp = request.getParameter("timestamp");
// 随机数
String nonce = request.getParameter("nonce");
// 随机字符串
String echostr = request.getParameter("echostr");
List<String> params = new ArrayList<String>();
params.add(Token);
params.add(timestamp);
params.add(nonce);
// 1. 将token、timestamp、nonce三个参数进行字典排序
Collections.sort(params, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
// 2. 将三个参数拼接成一个字符串进行SHA1进行加密
String temp = SHA1Utils.encode(params.get(0) + params.get(1)
+ params.get(2));
// 3. 加密后的字符串与signature比较,标识该请求是来自微信
if (temp.equals(signature)) {
// 原样返回echostr参数内容,则接入成功
response.getWriter().write(echostr);
log.debug("echostr传回微信后台成功...");
} else {
log.debug("echostr传回微信后台失败...");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding(Constants.CHARSET);
response.setCharacterEncoding(Constants.CHARSET);
PrintWriter out = response.getWriter();
String result = null;
Map<String, String> map = null;
try {
map = MessageUtils.xmlToMap(request);
} catch (DocumentException e1) {
e1.printStackTrace();
}
String toUserName = map.get("ToUserName");
String fromUserName = map.get("FromUserName");
String msgType = map.get("MsgType");
String content = map.get("Content");
String echostr = request.getParameter("echostr");
// 判断是否是微信接入激活验证,只有首次接入验证时才会收到echostr参数,此时需要把它直接返回
if (echostr != null && echostr.length() > 1) {
result = echostr;
} else {
// 判断请求是是否是文本类型 text
if (MessageUtils.MESSAGE_TEXT.equals(msgType)) {
if ("文艺".equals(content)) {
result = imageProcess(toUserName, fromUserName);
// String mediaId =
// "7u19uWKlh-Nfpm8dAEpkhgxr0u5y0H5hxARQKsqtv3FjcMOV9dtFGxpYU4RvaV4t";
// result = MessageUtils.initImageMessage(mediaId,
// toUserName,fromUserName);
} else if ("图文".equals(content)) {
result = MessageUtils.initArticlesMessage(toUserName,
fromUserName);
} else {
String api = "http://ctr.demo.xiaoi.com/robot/ask.action?";
try {
URLEncoder.encode(content, Constants.CHARSET);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 拼接url
StringBuffer bf = new StringBuffer();
bf.append("question=");
bf.append(content);
bf.append("&paltform=weixin");
String url = api + bf.toString();
String message = HttpUtils.get(url, Constants.CHARSET);
message = message.substring(
message.indexOf("<Content>") + 9,
message.indexOf("</Content>"));
result = MessageUtils.initTextMessage(message, toUserName,
fromUserName);
}
}
}
out.write(result);
out.close();
}
private String imageProcess(String toUserName, String fromUserName) {
String message = null;
AccessToken token = WechatUtils.getAccessToken();
String mediaId = null;
Random ran = new Random();
int i = ran.nextInt(28);
String filePath = "/app/ibot-odin-robot-8005/webapps/robot-dev/image/0" + (i+1) + ".jpg";
try {
mediaId = WechatUtils.upload(filePath, token.getToken(),
MessageUtils.MESSAGE_IMAGE);
// mediaId =
// "7u19uWKlh-Nfpm8dAEpkhgxr0u5y0H5hxARQKsqtv3FjcMOV9dtFGxpYU4RvaV4t";
} catch (Exception e) {
e.printStackTrace();
}
message = MessageUtils.initImageMessage(mediaId, toUserName,
fromUserName);
return message;
}
}

评论列表( 0 )

你可以在登录后,发表评论

搜索帮助