导入jar包:
dom4j-1.6.1.jar
xstream-1.3.1.jar
TextMessage
package com.jiuzhouchedai.po;
public class TextMessage {
private String ToUserName; //开发者微信号
private String FromUserName; //发送方帐号(一个OpenID)
private long CreateTime; //消息创建时间 (整型)
private String MsgType; //text
private String Content; //文本消息内容
private String MsgId; //消息id,64位整型
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;
}
public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
public String getMsgId() {
return MsgId;
}
public void setMsgId(String msgId) {
MsgId = msgId;
}
}
weixinServlet
package com.jiuzhouchedai.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jiuzhouchedai.po.TextMessage;
import com.jiuzhouchedai.util.CheckUtil;
import com.jiuzhouchedai.util.MessageUtil;
public class weixinServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String signature=request.getParameter("signature");
String timestamp=request.getParameter("timestamp");
String nonce=request.getParameter("nonce");
String echostr=request.getParameter("echostr");
PrintWriter out=response.getWriter();
if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
out.write(echostr);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out=response.getWriter();
try {
Map<String, String> map=MessageUtil.xmlToMap(request);
String toUserName=map.get("ToUserName");
String fromUserName= map.get("FromUserName");
String msgType=map.get("MsgType");
String content=map.get("Content");
String message=null;
if(MessageUtil.MESSAGE_TEXT.equals(msgType)){
if("1".equals(content)){
message=MessageUtil.initText(toUserName, fromUserName, MessageUtil.firstMenu());
}else if ("2".equals(content)) {
message=MessageUtil.initText(toUserName, fromUserName, MessageUtil.secondMenu());
}else if ("?".equals(content)||"?".equals(content)) {
message=MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
}else{
message=MessageUtil.initText(toUserName, fromUserName, MessageUtil.othersMenu());
}
}else if(MessageUtil.MESSAGE_EVENT.equals(msgType)){
String eventType=map.get("Event");
if (MessageUtil.MESSAGE_SUBSCRIBE.equals(eventType)) {
message=MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
}
}
out.print(message);
} catch (Exception e) {
e.printStackTrace();
}finally{
out.close();
}
}
}
CheckUtil
package com.jiuzhouchedai.util;
import java.lang.reflect.Array;
import java.security.MessageDigest;
import java.util.Arrays;
public class CheckUtil {
public static final String token="yusongtaochn";
public static boolean checkSignature(String signature,String timestamp,String nonce){
String[] arr=new String[]{token, timestamp, nonce};
//字典排序
Arrays.sort(arr);
//生成字符串
StringBuffer content=new StringBuffer();
for (int i = 0; i < arr.length; i++) {
content.append(arr[i]);
}
//sha1加密
String temp = getSha1(content.toString());
return temp.equals(signature);
}
public static String getSha1(String str){
if(str==null||str.length()==0){
return null;
}
char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f'};
try {
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes("UTF-8"));
byte[] md = mdTemp.digest();
int j = md.length;
char buf[] = new char[j*2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
} catch (Exception e) {
// TODO: handle exception
return null;
}
}
}
MessageUtil
package com.jiuzhouchedai.util;
import java.io.IOException;
import java.io.InputStream;
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.Element;
import org.dom4j.io.SAXReader;
import com.jiuzhouchedai.po.TextMessage;
import com.thoughtworks.xstream.XStream;
public class MessageUtil {
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";
public static Map<String, String> xmlToMap(HttpServletRequest request) throws Exception{
Map<String, String> map=new HashMap<String, String>();
SAXReader reader=new SAXReader();
InputStream ins = request.getInputStream();
Document doc = reader.read(ins);
Element root = doc.getRootElement();
List<Element> list = root.elements();
for (Element e : list) {
map.put(e.getName(), e.getText());
}
ins.close();
return map;
}
public static String textMessageToXml(TextMessage textMessage){
XStream stream=new XStream();
stream.alias("xml", textMessage.getClass());
return stream.toXML(textMessage);
}
public static String initText(String toUserName,String fromUserName,String content){
TextMessage text=new TextMessage();
text.setFromUserName(toUserName);
text.setToUserName(fromUserName);
text.setMsgType(MessageUtil.MESSAGE_TEXT);
text.setCreateTime(new Date().getTime());
text.setContent(content);
return textMessageToXml(text);
}
public static String menuText(){
StringBuffer sb=new StringBuffer();
sb.append("欢迎您的关注,请按照菜单提示操作:");
sb.append("1.学习内容简介\n");
sb.append("2.104简介\n");
sb.append("回复?调出此菜单。");
return sb.toString();
}
public static String firstMenu(){
StringBuffer sb=new StringBuffer();
sb.append("本社团教学:java、iOS、安卓、微信开发、大数据、ps、前端页面等技术。\n");
sb.append("回复?调出此菜单。");
return sb.toString();
}
public static String secondMenu(){
StringBuffer sb=new StringBuffer();
sb.append("104是IT极客社的大本营。里面汇聚了全球四面八方的极客大神。\n");
sb.append("回复?调出此菜单。");
return sb.toString();
}
public static String othersMenu(){
StringBuffer sb=new StringBuffer();
sb.append("请回复正确的菜单选项。\n");
sb.append("回复?调出此菜单。");
return sb.toString();
}
}