Java微信二次開發(fā)(二) Java微信文本消息接口請求與發(fā)送
第二篇,做微信文本消息接口請求與發(fā)送,具體內(nèi)容如下
需要導(dǎo)入庫:dom4j-1.6.1.jar,xstream-1.3.1.jar
第一步:新建包com.wtz.message.response,新建類BaseMessage.java
package com.wtz.message.response;
/**
* @author wangtianze QQ:864620012
* @date 2017年4月19日 下午3:12:40
* <p>version:1.0</p>
* <p>description:基礎(chǔ)消息類</p>
*/
public class BaseMessage {
//接收方
private String ToUserName;
//發(fā)送方
private String FromUserName;
//消息的創(chuàng)建時間
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;
}
}
第二步:找到包com.wtz.message.response,新建類TextMessage.java
package com.wtz.message.response;
/**
* @author wangtianze QQ:864620012
* @date 2017年4月19日 下午3:22:33
* <p>version:1.0</p>
* <p>description:文本消息類</p>
*/
public class TextMessage extends BaseMessage{
//消息內(nèi)容
private String Content;
public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
}
第三步:找到包com.wtz.util,新建類MessageUtil.java
package com.wtz.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.wtz.message.response.TextMessage;
/**
* @author wangtianze QQ:864620012
* @date 2017年4月19日 下午3:29:58
* <p>version:1.0</p>
* <p>description:消息處理工具類</p>
*/
public class MessageUtil {
//定義了消息類型(常量:文本類型)
public static final String RESP_MESSAGE_TYPE_TEXT = "text";
//從流中解析出每個節(jié)點的內(nèi)容
public static Map<String,String> parseXml(HttpServletRequest request) throws IOException{
Map<String,String> map = new HashMap<String,String>();
//從輸入流中獲取流對象
InputStream in = request.getInputStream();
//構(gòu)建SAX閱讀器對象
SAXReader reader = new SAXReader();
try {
//從流中獲得文檔對象
Document doc = reader.read(in);
//獲得根節(jié)點
Element root = doc.getRootElement();
//獲取根節(jié)點下的所有子節(jié)點
List<Element> children = root.elements();
for(Element e:children){
//遍歷每一個節(jié)點,并按照節(jié)點名--節(jié)點值放入map中
map.put(e.getName(), e.getText());
System.out.println("用戶發(fā)送的消息XML解析為:" + e.getName() + e.getText());
}
//關(guān)閉流
in.close();
in = null;
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map;
}
/**
* 用于擴(kuò)展節(jié)點數(shù)據(jù)按照<ToUserName><![CDATA[toUser]]></ToUserName>,中間加了CDATA段
*/
private static XStream xstream = new XStream(new XppDriver(){
public HierarchicalStreamWriter createWriter(Writer out){
return new PrettyPrintWriter(out){
boolean cdata = true;
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);
}
}
};
}
});
/**
* 將文本消息轉(zhuǎn)換成XML格式
*/
public static String messageToXml(TextMessage textMessage){
xstream.alias("xml",textMessage.getClass());
String xml = xstream.toXML(textMessage);
System.out.println("響應(yīng)所轉(zhuǎn)換的XML:"+xml);
return xml;
}
}
第四步:找到包com.wtz.service,新建類ProcessService.java
package com.wtz.util;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.wtz.message.response.TextMessage;
/**
* @author wangtianze QQ:864620012
* @date 2017年4月19日 下午8:04:14
* <p>version:1.0</p>
* <p>description:核心服務(wù)類</p>
*/
public class ProcessService {
public static String dealRequest(HttpServletRequest request) throws IOException{
//響應(yīng)的XML串
String respXml = "";
//要響應(yīng)的文本內(nèi)容
String respContent = "未知的消息類型";
Map<String,String> requestMap = MessageUtil.parseXml(request);
String fromUserName = requestMap.get("FromUserName");
String toUserName = requestMap.get("ToUserName");
String MsgType = requestMap.get("MsgType");
String Content = requestMap.get("Content");
System.out.println("用戶給公眾號發(fā)的消息為:" + Content);
//構(gòu)建一條文本消息
TextMessage textMessage = new TextMessage();
textMessage.setToUserName(fromUserName);
textMessage.setFromUserName(toUserName);
textMessage.setCreateTime(new Date().getTime());
textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
if(MsgType.equals(MessageUtil.RESP_MESSAGE_TYPE_TEXT)){
respContent = "王天澤的公眾號收到了您的一條文本消息:" + Content + ",時間戳是:" + (new Date().getTime());
}
textMessage.setContent(respContent);
respXml = MessageUtil.messageToXml(textMessage);
System.out.println("respXml:"+respXml);
return respXml;
}
}
第五步:找到包com.wtz.service下的LoginServlet類,重寫doPost方法
package com.wtz.service;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.wtz.util.MessageUtil;
import com.wtz.util.ProcessService;
import com.wtz.util.ValidationUtil;
/**
* @author wangtianze QQ:864620012
* @date 2017年4月17日 下午8:11:32
* <p>version:1.0</p>
* <p>description:微信請求驗證類</p>
*/
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("get請求。。。。。。");
//1.獲得微信簽名的加密字符串
String signature = request.getParameter("signature");
//2.獲得時間戳信息
String timestamp = request.getParameter("timestamp");
//3.獲得隨機數(shù)
String nonce = request.getParameter("nonce");
//4.獲得隨機字符串
String echostr = request.getParameter("echostr");
System.out.println("獲得微信簽名的加密字符串:"+signature);
System.out.println("獲得時間戳信息:"+timestamp);
System.out.println("獲得隨機數(shù):"+nonce);
System.out.println("獲得隨機字符串:"+echostr);
PrintWriter out = response.getWriter();
//驗證請求確認(rèn)成功原樣返回echostr參數(shù)內(nèi)容,則接入生效,成為開發(fā)者成功,否則失敗
if(ValidationUtil.checkSignature(signature, timestamp, nonce)){
out.print(echostr);
}
out.close();
out = null;
}
/**
* 接受微信服務(wù)器發(fā)過來的XML數(shù)據(jù)包(通過post請求發(fā)送過來的)
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//獲取微信加密的簽名字符串
String signature = request.getParameter("signature");
//獲取時間戳
String timestamp = request.getParameter("timestamp");
//獲取隨機數(shù)
String nonce = request.getParameter("nonce");
PrintWriter out = response.getWriter();
if(ValidationUtil.checkSignature(signature,timestamp,nonce)){
String respXml = "";
try {
respXml = ProcessService.dealRequest(request);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.print(respXml);
}
out.close();
out = null;
}
}
完成微信文本消息接口請求與發(fā)送。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于報錯IDEA Terminated with exit code
如果在IDEA構(gòu)建項目時遇到下面這樣的報錯IDEA Terminated with exit code 1,那必然是Maven的設(shè)置參數(shù)重置了,導(dǎo)致下載錯誤引起的,本文給大家分享兩種解決方法,需要的朋友可以參考下2022-08-08
Java transient關(guān)鍵字與序列化操作實例詳解
這篇文章主要介紹了Java transient關(guān)鍵字與序列化操作,結(jié)合實例形式詳細(xì)分析了java序列化操作相關(guān)實現(xiàn)方法與操作注意事項,需要的朋友可以參考下2019-09-09
IntelliJ?IDEA?2022.1.1?沒有CVS的過程分析
這篇文章主要介紹了IntelliJ?IDEA?2022.1.1?沒有CVS的過程解析,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-07-07

