您的位置:首页 > 移动开发 > 微信开发

微信公众号开发(2)——文本消息、图文消息发送

2018-12-30 10:28 555 查看

接上一讲,微信公众号开发(1)——服务器配置

新建几个信息类:

[code]package com.imooc.po;

/**
* 信息基类
* @author lyj
*
*/
public class BaseMessage {

private String ToUserName;
private String FromUserName;
private Long CreateTime;
private String MsgType;
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;
}

}

[code]package com.imooc.po;

/**
* 文本消息类封装
* @author lyj
*
*/
public class TextMessage extends BaseMessage{

private String Content;
private String MsgId;

public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
public String getMsgId() {
return MsgId;
}
public void setMsgId(String msgId) {
MsgId = msgId;
}

}

[code]package com.imooc.po;

/**
* 图文消息类
* @author lyj
*
*/
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;
}

}

 

[code]package com.imooc.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;
}

}

 

需要的jar包:

MessageUtil.java工具类的详细代码:

[code]package com.imooc.util;

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.imooc.po.News;
import com.imooc.po.NewsMessage;
import com.imooc.po.TextMessage;
import com.thoughtworks.xstream.XStream;

public class MessageUtil {

public static final String MESSAGE_TEXT="text";
public static final String MESSAGE_NEWS="news";
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_LOCARION="location";
public static final String MESSAGE_EVENT="event";
public static final String MESSAGE_SUBSCRIBE="subscribe";
public static final String MESSAGE_CLICK="CLICK";
public static final String MESSAGE_VIEW="VIEW";

/**
* xml文件转换为Map集合
* @param request
* @return
* @throws Exception
*/
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;
}
/**
* 将文本对象转换为xml
* @param textMessage
* @return
*/
public static String textMessageToXml(TextMessage textMessage) {
XStream xstream=new XStream();
xstream.alias("xml", textMessage.getClass());
return xstream.toXML(textMessage);
}
/**
* 将图文消息转换为xml
* @param newsMessage
* @return
*/
public static String newsMessageToXml(NewsMessage newsMessage) {
XStream xstream=new XStream();
xstream.alias("xml", newsMessage.getClass());//将根节点转换为<xml></xml>
xstream.alias("item", new News().getClass());
return xstream.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);
}

/**
*主 菜单
* @return
*/
public static String menuText() {
StringBuffer sb=new StringBuffer();
sb.append("欢迎您的关注,请按照菜单提示开始操作:\n\n");
sb.append("1:朱一龙介绍\n");
sb.append("2:朱一龙出演过的作品\n\n");
sb.append("回复?调出此菜单.");
return sb.toString();

}

public static String firstMenu() { //用户输入“1"时服务器回复的消息
StringBuffer sb=new StringBuffer();
sb.append("朱一龙,1988年4月16日出生于湖北武汉,中国内地男演员,毕业于北京电影学院2006级表演系本科。");
return sb.toString();
}
public static String secondMenu() { //用户输入"2"时回复的消息
StringBuffer sb=new StringBuffer();
sb.append("2009年出演首部电影《再生缘》,后参演多部《周末王刚讲故事》(又名:《儿女传奇》)系列数字电影;2010年参演古装系列电影《大明嫔妃》 [1]  ;2012年在家庭情感轻喜剧《家宴》中饰演冯豆子 [2]  ;2014年在民国爱情剧《情定三生》中饰演豪门少爷迟瑞,随后,凭借该角色于2015年1月26日获得亚洲影响力东方盛典最具潜力男演员奖;2015年因在古装历史剧《芈月传》中饰演秦昭襄王嬴稷而受到广泛关注 [3]  ;2016年2月,在古装武侠剧《新萧十一郎》中饰演风采翩翩、文武兼备的无垢山庄少庄主连城璧 [4]  ;7月,在武侠小说《新边城浪子》中饰演黑衣黑刀傅红雪 [5]  。2017年,主演年代爱情剧《许你浮生若梦》 [6]  。2018年6月主演奇幻网络剧《镇魂》,分饰沈巍、夜尊、黑袍使三角,凭借精湛演绎人气飙升,同时为该剧演唱推广曲《时间飞行》 [7-8]  。10月,悬疑冒险剧《盗墓笔记重启》开机,饰演吴邪。");
return sb.toString();
}

/**
* 图文消息的组装
* @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("朱一龙");
news.setDescription("2009年4月,在电影《再生缘》中饰演刺客阮应");
news.setPicUrl("http://example.ngrok.xiaomiqiu.cn/WeiXin/image/朱一龙.jpg");
news.setUrl("www.baidu.com");

News news2=new News();
news2.setTitle("朱哥");
news2.setDescription("当公众号具备留言功能以留言,或仅公众号粉丝可以留言)。");
news2.setPicUrl("http://example.ngrok.xiaomiqiu.cn/WeiXin/image/jiajingwen-001.jpg");
news2.setUrl("www.baidu.com");

newsList.add(news);
newsList.add(news2);

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;

}
}

WeixinServlet.java里面添加doPost相关代码:

[code]@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

resp.setCharacterEncoding("UTF-8");
req.setCharacterEncoding("utf-8");
PrintWriter out=resp.getWriter();
Map<String, String> map;
try {
map = MessageUtil.xmlToMap(req);
String FromUserName=map.get("FromUserName");
String ToUserName=map.get("ToUserName");
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.initNewsMessage(ToUserName, FromUserName);
}else if("?".equals(Content)||"?".equals(Content)) {
message=MessageUtil.initText(ToUserName, FromUserName, MessageUtil.menuText());
}else {
message=MessageUtil.initText(ToUserName, FromUserName, "晴晴,能不能好好输,别乱输");
}
/*
TextMessage text=new TextMessage();
text.setFromUserName(ToUserName);
text.setToUserName(FromUserName);
text.setMsgType("text");
text.setCreateTime(new Date().getTime());
text.setContent("您发送的消息是:"+Content);
message=MessageUtil.textMessageToXml(text); */
}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());
}
}
System.out.println(message);
out.print(message);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
out.close();
}

}

至此,大功告成,用户输入相应的数字或字符,微信后台就可以回复对应的文本消息和图文消息了。

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: