慕课网图文消息

微信官网的开发者文档

发送消息-被动回复消息

 

可以了,按2回复图文消息

下面贴一下代码吧

WX_Interface.java

package net.wxinterface;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.DocumentException;

import com.imooc.po.TextMessage;
import com.imooc.util.MessageUtil;
public class WX_Interface extends HttpServlet {

/**
* Constructor of the object.
*/
public WX_Interface() {
super();
}

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//微信加密签名,signature结合了开发者填写的tocken参数和请求中的timestamp参数、nonce参数。
String signature = request.getParameter("signature");
//时间戳
String timestamp = request.getParameter("timestamp");
//随机数
String nonce = request.getParameter("nonce");

String echostr = request.getParameter("echostr");

String tocken = "test";
try{
if(null != signature){
String[] ArrTmp = {tocken,timestamp,nonce};
Arrays.sort(ArrTmp);
StringBuffer sb = new StringBuffer();
for(int i=0;i<ArrTmp.length;i++){
sb.append(ArrTmp[i]);
}
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] bytes = md.digest(new String(sb).getBytes());
StringBuffer buf = new StringBuffer();
for(int i=0;i<bytes.length;i++){
if(((int)bytes[i] & 0xff)<0x10){
buf.append("0");
}
buf.append(Long.toString((int) bytes[i] & 0xff,16));

}
if(signature.equals(buf.toString())){
response.getOutputStream().println(echostr);
}
}
}catch(Exception e){
e.printStackTrace();
}

System.out.println("test0");


System.out.println("doGet");
System.out.println("signature "+signature);
System.out.println("timstamp "+timestamp);
System.out.println("nonce "+nonce);
System.out.println("echostr "+echostr);


System.out.println("doGet");

}

/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
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 fromUserName = map.get("FromUserName");
String toUserName = map.get("ToUserName");
String msgType = map.get("MsgType");
String content = map.get("Content");//
String message = null;

//if("text".equals(msgType)){
if(MessageUtil.MESSAGE_TEXT.equals(msgType)){
if("1".equals(content)){
message = MessageUtil.initText(toUserName,fromUserName,MessageUtil.firstMenu());
}else if("3".equals(content)){
message = MessageUtil.initText(toUserName,fromUserName,content);
}else if("2".equals(content)){
//message = MessageUtil.initText(toUserName,fromUserName,MessageUtil.secondMenu());
message = MessageUtil.initNewsMessage(toUserName,fromUserName);//用户按2返回图文消息
//整个的图文消息的创建以及回复已经写完了
}else if("?".equals(content)||" ? ".equals(content)){
message = MessageUtil.initText(toUserName,fromUserName,MessageUtil.menuText());
}
/* 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);

System.out.println(message);*/
}else if(MessageUtil.MESSAGE_EVENT.equals(msgType)){//添加消息推送的逻辑
String eventType = map.get("Event");
if(MessageUtil.MESSAGE_SUBSCRIBE.equals(eventType)){//消息推送事件的类型
message = MessageUtil.initText(toUserName, fromUserName, content);//关注微信公众号之后微信后台推送
}

}
out .print(message);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
out.close();
}

System.out.println("doPost");
//response.setContentType("text/html");
//PrintWriter out = response.getWriter();

/* StringBuffer strb = new StringBuffer();
ServletInputStream in = request.getInputStream();
BufferedReader breader= new BufferedReader( new InputStreamReader(in,"UTF-8"));

String str = null;
while(null!=(str=breader.readLine())){
strb.append(str);
}
//out.println(str);
System.out.println(strb);*/
//out.flush();
//out.close();
}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}

}

MessageUtil.java

package com.imooc.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 javax.xml.soap.Text;

import org.dom4j.Document;
import org.dom4j.DocumentException;
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_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";
/**
* xml转为map集合
* @param ${param} the ${bare_field_name} to set
* @param ${param} the ${bare_field_name} to set
* @param ${param} the ${bare_field_name} to set
* @param ${param} the ${bare_field_name} to set
*/

public static Map<String,String> xmlToMap(HttpServletRequest request) throws DocumentException, IOException{
Map<String,String> map = new HashMap<String,String>();
SAXReader reader = new SAXReader();
InputStream ins = request.getInputStream();//从request中获取输入流
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 ${param} the ${bare_field_name} to set
* @param ${param} the ${bare_field_name} to set
* @param ${param} the ${bare_field_name} to set
* @param ${param} the ${bare_field_name} to set
*/

public static String textMessageToXml(TextMessage textMessage){
XStream xstream = new XStream();
xstream.alias("xml",textMessage.getClass());
return xstream.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_EVENT);//这里写错了 导致不能提供服务
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("欢迎您的关注,请按照菜单提示进行操作: ");
sb.append("1、课程介绍");
sb.append("2、慕课网介绍 ");
sb.append("回复?调出此菜单。");
return sb.toString();

}

public static String firstMenu(){
StringBuffer sb = new StringBuffer();
sb.append("本套课程介绍微信公众号开发,主要涉及公众号介绍、编辑模式介绍、开发模式介绍等");
return sb.toString();
}

public static String secondMenu(){
StringBuffer sb = new StringBuffer();
sb.append("慕课网是垂直的互联网IT技能免费学习网站。以独家视频教程、在线编程工具、学习计划、问答社区为核心特色。在这里,你可以找到最好的互联网技术牛人,也可以通过免费的在线公开视频课程学习国内领先的互联网IT技术。");
sb.append("慕课网课程涵盖前端开发、PHP、Html5、Android、iOS、Swift等IT前沿技术语言,包括基础课程、实用案例、高级分享三大类型,适合不同阶段的学习人群。以纯干货、短视频的形式为平台特点,为在校学生、职场白领提供了一个迅速提升技能、共同分享进步的学习平台。[1]");
sb.append("4月2日,国内首个IT技能学习类应用——慕课网3.1.0版本在应用宝首发。据了解,在此次上线的版本中,慕课网新增了课程历史记录、相关课程推荐等四大功能,为用户营造更加丰富的移动端IT学习体验");

return sb.toString();
}
/***
* 把图文消息的实例对象转化为XML格式的数据
* 图文消息转为XML
* 图文消息的组装
*
*
*/
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对象并分别赋值最后一并导入集合newsList里面

news.setTitle("慕课网介绍");
news.setDescription("慕课网是垂直的互联网IT技能免费学习网站。以独家视频教程、在线编程工具、学习计划、问答社区为核心特色。在这里,你可以找到最好的互联网技术牛人,也可以通过免费的在线公开视频课程学习国内领先的互联网IT技术。慕课网课程涵盖前端开发、PHP、Html5、Android、iOS、Swift等IT前沿技术语言,包括基础课程、实用案例、高级分享三大类型,适合不同阶段的学习人群。以纯干货、短视频的形式为平台特点,为在校学生、职场白领提供了一个迅速提升技能、共同分享进步的学习平台。[1] 4月2日,国内首个IT技能学习类应用——慕课网3.1.0版本在应用宝首发。据了解,在此次上线的版本中,慕课网新增了课程历史记录、相关课程推荐等四大功能,为用户营造更加丰富的移动端IT学习体验。[2] ");
//news.setPicUrl("wx2017.duapp.com/beifeng/image/imooc.jpg");//服务器中图片的路径

news.setPicUrl("http://wx2017.duapp.com/beifeng/image/imooc.jpg");//服务器中图片的路径  注意图片的路径不要忘记加上http  否则图片地址是错误的读取不到图片

news.setUrl("www.imooc.com");//跳转的路径 慕课网的官网

newsList.add(news);//这一条图文消息设置完毕之后就把它放置到集合里面
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);//把图文消息实例对象转换为XML数据
return message;
}
public static String newsMessageToXml(NewsMessage newsMessage){
XStream xstream = new XStream();
xstream.alias("xml",newsMessage.getClass());//把图文消息NewsMessage->xml
xstream.alias("item",new News().getClass());//把消息体News -> item
return xstream.toXML(newsMessage);
}
}

News.java

package com.imooc.po;
//图文消息最里层的四个属性
public class News {
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;
}
private String Title;//标题
private String Description;//标题图片描述
private String PicUrl;//图片地址
private String Url;//跳转地址

}

NewsMessage.java

package com.imooc.po;
//图文消息的实例对象
import java.util.List;

//图文消息的最外层部分
//NewsMessage图文消息也是一样 继承父类BaseMessage
//微信公众后台它只能接收XML格式的数据
public class NewsMessage extends BaseMessage{
private int ArticleCount;//图文消息的数量 个数 限制在8条以内
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;
}

}

BaseMessage.java

package com.imooc.po;
//重复的东西就放在一个父类里面 重复的东西就没有必要重复的编写代码
public class BaseMessage {
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 getToUserName() {
return ToUserName;
}
public void setToUserName(String toUserName) {
ToUserName = toUserName;
}
private String FromUserName;//发送方账号(一个OpenID)
private String ToUserName;//开发者微信号
private long CreateTime;//消息创建时间(整型)
private String MsgType;//消息类型 text
}

修改了Mesageutil.java里面的图文消息类的图片路径之后再测试就成功了

原文地址:https://www.cnblogs.com/ZHONGZHENHUA/p/6278166.html