Java--對接微信第二篇之訂閱傳送圖文訊息給使用者
阿新 • • 發佈:2018-12-19
在第二篇的基礎上,把訂閱響應事件下的,傳送文字訊息介面替換成傳送圖文訊息的介面。
// 建立圖文訊息 NewsMessage newsMessage = new NewsMessage(); newsMessage.setToUserName(fromUserName); newsMessage.setFromUserName(toUserName); newsMessage.setCreateTime(System.currentTimeMillis()); newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS); newsMessage.setFuncFlag(0); List<Article> articleList = new ArrayList<Article>(); Article article = new Article(); article.setTitle("達達超人"); article.setDescription("謝謝您的關注"); article.setPicUrl("https://avatar.csdn.net/1/E/1/3_qq_31122833.jpg"); article.setUrl("https://blog.csdn.net/qq_31122833"); articleList.add(article); newsMessage.setArticleCount(articleList.size()); newsMessage.setArticles(articleList); message = MessageUtil.newsMessageToXml(newsMessage);
其中:NewsMessage
public class NewsMessage extends BaseMessage { // 圖文訊息個數,限制為10條以內 private int ArticleCount; // 多條圖文訊息資訊,預設第一個item為大圖 private List<Article> Articles; public int getArticleCount() { return ArticleCount; } public void setArticleCount(int articleCount) { ArticleCount = articleCount; } public List<Article> getArticles() { return Articles; } public void setArticles(List<Article> articles) { Articles = articles; } }
Article:
public class Article { // 圖文訊息名稱 private String Title; // 圖文訊息描述 private String Description; // 圖片連結,支援JPG、PNG格式,較好的效果為大圖640*320,小圖80*80,限制圖片連結的域名需要與開發者填寫的基本資料中的Url一致 private String PicUrl; // 點選圖文訊息跳轉連結 private String Url; public String getTitle() { return Title; } public void setTitle(String title) { Title = title; } public String getDescription() { return null == Description ? "" : Description; } public void setDescription(String description) { Description = description; } public String getPicUrl() { return null == PicUrl ? "" : PicUrl; } public void setPicUrl(String picUrl) { PicUrl = picUrl; } public String getUrl() { return null == Url ? "" : Url; } public void setUrl(String url) { Url = url; } }
MessageUtil:
public class MessageUtil {
private static Logger logger = Logger.getLogger(MessageUtil.class);
/**
* 返回訊息型別:文字
*/
public static final String RESP_MESSAGE_TYPE_TEXT = "text";
/**
* 返回訊息型別:音樂
*/
public static final String RESP_MESSAGE_TYPE_MUSIC = "music";
/**
* 返回訊息型別:圖文
*/
public static final String RESP_MESSAGE_TYPE_NEWS = "news";
/**
* 請求訊息型別:文字
*/
public static final String REQ_MESSAGE_TYPE_TEXT = "text";
/**
* 請求訊息型別:圖片
*/
public static final String REQ_MESSAGE_TYPE_IMAGE = "image";
/**
* 請求訊息型別:連結
*/
public static final String REQ_MESSAGE_TYPE_LINK = "link";
/**
* 請求訊息型別:地理位置
*/
public static final String REQ_MESSAGE_TYPE_LOCATION = "location";
/**
* 請求訊息型別:音訊
*/
public static final String REQ_MESSAGE_TYPE_VOICE = "voice";
/**
* 請求訊息型別:推送
*/
public static final String REQ_MESSAGE_TYPE_EVENT = "event";
/**
* 事件型別:群發訊息返回
*/
public static final String EVENT_TYPE_MASSSENDJOBFINISH = "MASSSENDJOBFINISH";
/**
* 事件型別:小程式稽核通過
*/
public static final String EVENT_TYPE_SMALLLROUTINE_PASS = "weapp_audit_success";
/**
* 事件型別:小程式稽核通過
*/
public static final String EVENT_TYPE_SMALLLROUTINE_FAIL = "weapp_audit_fail";
/**
* 事件型別:subscribe(訂閱)
*/
public static final String EVENT_TYPE_SUBSCRIBE = "subscribe";
/**
* 事件型別:LOCATION(地理位置推送)
*/
public static final String EVENT_TYPE_LOCATION = "LOCATION";
/**
* 事件型別:unsubscribe(取消訂閱)
*/
public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe";
/**
* 領取卡券事件
*/
public static final String EVENT_TYPE_USER_GET_CARD="user_get_card";
public static final String EVENT_TYPE_COUPONS_GET = "GetCoupons";
/**
* 卡券稽核通過
*/
public static final String EVENT_TYPE_CARD_PASS_CHECK="card_pass_check";
/**
* 使用者刪除卡券
*/
public static final String EVENT_USER_DEL_CARD="user_del_card";
/**
* 卡券稽核不通過
*/
public static final String EVENT_TYPE_CARD_NOT_PASS_CHECK="card_not_pass_check";
/**
* 微信自定義選單文字點選事件
*/
public static final String EVENT_TYPE_WECHATMENU_TEXT_CHECK="wechat_menu_text";
/**
* 微信自定義選單圖文點選事件
*/
public static final String EVENT_TYPE_WECHATMENU_NEWS_CHECK="wechat_menu_news";
/**
*
*/
public static final String EVENT_TYPE_WIFI_CONNECT ="WifiConnected";
/**
* 微信門店稽核通過
*/
public static final String EVENT_TYPE_POI_CHECK_NOTIFY="poi_check_notify";
/**
* 事件型別:CLICK(自定義選單點選事件)
*/
public static final String EVENT_TYPE_CLICK = "CLICK";
/*
* 組裝文字訊息
*/
public static String textMsg(String toUserName,String fromUserName,String content){
TextMessage text = new TextMessage();
text.setFromUserName(toUserName);
text.setToUserName(fromUserName);
text.setMsgType(REQ_MESSAGE_TYPE_TEXT);
text.setCreateTime(new Date().getTime());
text.setContent(content);
return textMessageToXml(text);
}
/*
* 響應訂閱事件--回覆文字訊息
*/
public static String subscribeForText(String toUserName,String fromUserName){
return textMsg(toUserName, fromUserName, "歡迎關注,精彩內容不容錯過!!!");
}
/*
* 響應取消訂閱事件
*/
public static String unsubscribe(String toUserName,String fromUserName){
//TODO 可以進行取關後的其他後續業務處理
System.out.println("使用者:"+ fromUserName +"取消關注~");
return "";
}
/**
* 解析微信發來的請求(XML)
*
* @param request
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
// 將解析結果儲存在HashMap中
Map<String, String> map = new HashMap<String, String>();
// 從request中取得輸入流
InputStream inputStream = request.getInputStream();
// 讀取輸入流
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
// 得到xml根元素
Element root = document.getRootElement();
// 得到根元素的所有子節點
List<Element> elementList = root.elements();
// 遍歷所有子節點
for (Element e : elementList)
map.put(e.getName(), e.getText());
// 釋放資源
inputStream.close();
inputStream = null;
return map;
}
/**
* 文字訊息物件轉換成xml
*
* @param textMessage 文字訊息物件
* @return xml
*/
public static String textMessageToXml(TextMessage textMessage) {
xstream.alias("xml", textMessage.getClass());
return xstream.toXML(textMessage);
}
/**
* 文字訊息物件轉換成xml
*
* @param voiceMessage 語音訊息物件
* @return xml
*/
public static String messageToXml(VoiceMessage voiceMessage) {
xstream.alias("xml", voiceMessage.getClass());
return xstream.toXML(voiceMessage);
}
/**
* 文字訊息物件轉換成xml
*
* @param videoMessage 視訊訊息物件
* @return xml
*/
public static String messageToXml(VideoMessage videoMessage) {
xstream.alias("xml", videoMessage.getClass());
return xstream.toXML(videoMessage);
}
/**
* 音樂訊息物件轉換成xml
*
* @param musicMessage 音樂訊息物件
* @return xml
*/
public static String musicMessageToXml(MusicMessage musicMessage) {
xstream.alias("xml", musicMessage.getClass());
return xstream.toXML(musicMessage);
}
/**
* 圖文訊息物件轉換成xml
*
* @param newsMessage 圖文訊息物件
* @return xml
*/
public static String newsMessageToXml(NewsMessage newsMessage) {
xstream.alias("xml", newsMessage.getClass());
xstream.alias("item", new Article().getClass());
return xstream.toXML(newsMessage);
}
/**
* 擴充套件xstream,使其支援CDATA塊
*
* @date 2013-05-19
*/
private static XStream xstream = new XStream(new XppDriver() {
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
// 對所有xml節點的轉換都增加CDATA標記
boolean cdata = true;
@SuppressWarnings("unchecked")
public void startNode(String name, Class clazz) {
super.startNode(name, clazz);
}
protected void writeText(QuickWriter writer, String text) {
if (cdata) {
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
} else {
writer.write(text);
}
}
};
}
});
/**
* 判斷是否是QQ表情
*
* @param content
* @return
*/
public static boolean isQqFace(String content) {
boolean result = false;
// 判斷QQ表情的正則表示式
String qqfaceRegex = "/::\\)|/::~|/::B|/::\\||/:8-\\)|/::<|/::$|/::X|/::Z|/::'\\(|/::-\\||/::@|/::P|/::D|/::O|/::\\(|/::\\+|/:--b|/::Q|/::T|/:,@P|/:,@-D|/::d|/:,@o|/::g|/:\\|-\\)|/::!|/::L|/::>|/::,@|/:,@f|/::-S|/:\\?|/:,@x|/:,@@|/::8|/:,@!|/:!!!|/:xx|/:bye|/:wipe|/:dig|/:handclap|/:&-\\(|/:B-\\)|/:<@|/:@>|/::-O|/:>-\\||/:P-\\(|/::'\\||/:X-\\)|/::\\*|/:@x|/:8\\*|/:pd|/:<W>|/:beer|/:basketb|/:oo|/:coffee|/:eat|/:pig|/:rose|/:fade|/:showlove|/:heart|/:break|/:cake|/:li|/:bome|/:kn|/:footb|/:ladybug|/:shit|/:moon|/:sun|/:gift|/:hug|/:strong|/:weak|/:share|/:v|/:@\\)|/:jj|/:@@|/:bad|/:lvu|/:no|/:ok|/:love|/:<L>|/:jump|/:shake|/:<O>|/:circle|/:kotow|/:turn|/:skip|/:oY|/:#-0|/:hiphot|/:kiss|/:<&|/:&>";
Pattern p = Pattern.compile(qqfaceRegex);
Matcher m = p.matcher(content);
if (m.matches()) {
result = true;
}
return result;
}
/**
* 演示Java中常用的獲取long型別時間的兩種方式
*/
public static void main(String[] args) {
long longTime = 1373206143378L;
String stdFormatTime = formatTime(longTime);
// 輸出格式:2013-07-07 22:09:03
logger.info(stdFormatTime);
}
/**
* 將long型別的時間轉換成標準格式(yyyy-MM-dd HH:mm:ss)
*
* @param longTime
* @return
*/
public static String formatTime(long longTime) {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return format.format(new Date(longTime));
}
}
效果: