导入jar包:
dom4j-1.6.1.jar
xstream-1.3.1.jar
上传两个图片:
00.jpg
11.png
BaseMessage
package com.jiuzhouchedai.po;
public class BaseMessage {
private String ToUserName; //开发者微信号
private String FromUserName; //发送方帐号(一个OpenID)
private long CreateTime; //消息创建时间 (整型)
private String MsgType; //text
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;
}
}
News
package com.jiuzhouchedai.po;
public class News {
private String Title;
private String Description;
private String PicUrl;
private String Url;
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public String getPicUrl() {
return PicUrl;
}
public void setPicUrl(String picUrl) {
PicUrl = picUrl;
}
public String getUrl() {
return Url;
}
public void setUrl(String url) {
Url = url;
}
}
NewsMessage
package com.jiuzhouchedai.po;
import java.util.List;
public class NewsMessage extends BaseMessage{
private int ArticleCount;
private List<News> Articles;
public int getArticleCount() {
return ArticleCount;
}
public void setArticleCount(int articleCount) {
ArticleCount = articleCount;
}
public List<News> getArticles() {
return Articles;
}
public void setArticles(List<News> articles) {
Articles = articles;
}
}
TextMessage
package com.jiuzhouchedai.po;
public class TextMessage extends BaseMessage{
private String Content; //文本消息内容
private String MsgId; //消息id,64位整型
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 ("3".equals(content)) {
message=MessageUtil.initNewsMessage(toUserName, fromUserName);
}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.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.Element;
import org.dom4j.io.SAXReader;
import com.jiuzhouchedai.po.News;
import com.jiuzhouchedai.po.NewsMessage;
import com.jiuzhouchedai.po.TextMessage;
import com.thoughtworks.xstream.XStream;
public class MessageUtil {
public static final String MESSAGE_NEWS="news";
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);
}
/*
* 图文消息转为xml
*/
public static String newsMessageToXml(NewsMessage newsMessage){
XStream stream=new XStream();
stream.alias("xml", newsMessage.getClass());
stream.alias("item", new News().getClass());
return stream.toXML(newsMessage);
}
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);
}
/**
* 图文消息的组装
* @param toUserName
* @param fromUserName
* @return
*/
public static String initNewsMessage(String toUserName,String fromUserName){
String message=null;
List<News> newsList=new ArrayList<News>();
NewsMessage newsMessage=new NewsMessage();
News news=new News();
news.setTitle("IT极客社介绍");
news.setDescription("IT极客社是齐齐哈尔大学唯一一个IT相关的社团,有成员250多人,各个都是计算机领域的大神。");
news.setPicUrl("http://www.jiuzhouchedai.com/weixintest/img/11.png");
news.setUrl("www.jiuzhouchedai.com");
newsList.add(news);
News news1=new News();
news1.setTitle("优秀学子介绍");
news1.setDescription("ddddddddddddddddddddddddddddddd");
news1.setPicUrl("http://www.jiuzhouchedai.com/weixintest/img/00.png");
news1.setUrl("www.jiuzhouchedai.com");
newsList.add(news1);
newsMessage.setToUserName(fromUserName);
newsMessage.setFromUserName(toUserName);
newsMessage.setCreateTime(new Date().getTime());
newsMessage.setMsgType(MESSAGE_NEWS);
newsMessage.setArticles(newsList);
newsMessage.setArticleCount(newsList.size());
message= newsMessageToXml(newsMessage);
return message;
}
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();
}
}