首先定義一個類InputMessage? 接受微信發(fā)過來的消息煌往,微信穿過來的消息主要有曙寡,文字(用戶輸入的)糠爬,點擊事件(按鈕),圖片举庶,語音执隧,鏈接,位置等等具體代碼如下:```import java.io.Serializable;import com.thoughtworks.xstream.annotations.XStreamAlias;@XStreamAlias("xml")? public class InputMessage implements Serializable {? ? ? ? /**? ? ? *? ? ? */? ? ? private static final long serialVersionUID = 1L;? ? ? @XStreamAlias("ToUserName")? ? ? private String ToUserName;? ? ? @XStreamAlias("FromUserName")? ? ? private String FromUserName;? ? ? @XStreamAlias("CreateTime")? ? ? private Long CreateTime;? ? ? @XStreamAlias("MsgType")? ? ? private String MsgType = "text";? ? ? @XStreamAlias("MsgId")? ? ? private Long MsgId;? ? ? // 文本消息? ? ? @XStreamAlias("Content")? ? ? private String Content;? ? ? // 圖片消息? ? ? @XStreamAlias("PicUrl")? ? ? private String PicUrl;? ? ? // 位置消息? ? ? @XStreamAlias("LocationX")? ? ? private String LocationX;? ? ? @XStreamAlias("LocationY")? ? ? private String LocationY;? ? ? @XStreamAlias("Scale")? ? ? private Long Scale;? ? ? @XStreamAlias("Label")? ? ? private String Label;? ? ? // 鏈接消息? ? ? @XStreamAlias("Title")? ? ? private String Title;? ? ? @XStreamAlias("Description")? ? ? private String Description;? ? ? @XStreamAlias("Url")? ? ? private String URL;? ? ? // 語音信息? ? ? @XStreamAlias("MediaId")? ? ? private String MediaId;? ? ? @XStreamAlias("Format")? ? ? private String Format;? ? ? @XStreamAlias("Recognition")? ? ? private String Recognition;? ? ? // 事件? ? ? @XStreamAlias("Event")? ? ? private String Event;? ? ? @XStreamAlias("EventKey")? ? ? private String EventKey;? ? ? @XStreamAlias("Ticket")? ? ? private String Ticket;? ? ? ? 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;? ? ? }? ? ? ? public Long getMsgId() {? ? ? ? ? return MsgId;? ? ? }? ? ? ? public void setMsgId(Long msgId) {? ? ? ? ? MsgId = msgId;? ? ? }? ? ? ? public String getContent() {? ? ? ? ? return Content;? ? ? }? ? ? ? public void setContent(String content) {? ? ? ? ? Content = content;? ? ? }? ? ? ? public String getPicUrl() {? ? ? ? ? return PicUrl;? ? ? }? ? ? ? public void setPicUrl(String picUrl) {? ? ? ? ? PicUrl = picUrl;? ? ? }? ? ? ? public String getLocationX() {? ? ? ? ? return LocationX;? ? ? }? ? ? ? public void setLocationX(String locationX) {? ? ? ? ? LocationX = locationX;? ? ? }? ? ? ? public String getLocationY() {? ? ? ? ? return LocationY;? ? ? }? ? ? ? public void setLocationY(String locationY) {? ? ? ? ? LocationY = locationY;? ? ? }? ? ? ? public Long getScale() {? ? ? ? ? return Scale;? ? ? }? ? ? ? public void setScale(Long scale) {? ? ? ? ? Scale = scale;? ? ? }? ? ? ? public String getLabel() {? ? ? ? ? return Label;? ? ? }? ? ? ? public void setLabel(String label) {? ? ? ? ? Label = label;? ? ? }? ? ? ? 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 getURL() {? ? ? ? ? return URL;? ? ? }? ? ? ? public void setURL(String uRL) {? ? ? ? ? URL = uRL;? ? ? }? ? ? ? public String getEvent() {? ? ? ? ? return Event;? ? ? }? ? ? ? public void setEvent(String event) {? ? ? ? ? Event = event;? ? ? }? ? ? ? public String getEventKey() {? ? ? ? ? return EventKey;? ? ? }? ? ? ? public void setEventKey(String eventKey) {? ? ? ? ? EventKey = eventKey;? ? ? }? ? ? ? public String getMediaId() {? ? ? ? ? return MediaId;? ? ? }? ? ? ? public void setMediaId(String mediaId) {? ? ? ? ? MediaId = mediaId;? ? ? }? ? ? ? public String getFormat() {? ? ? ? ? return Format;? ? ? }? ? ? ? public void setFormat(String format) {? ? ? ? ? Format = format;? ? ? }? ? ? ? public String getRecognition() {? ? ? ? ? return Recognition;? ? ? }? ? ? ? public void setRecognition(String recognition) {? ? ? ? ? Recognition = recognition;? ? ? }? ? ? ? public String getTicket() {? ? ? ? ? return Ticket;? ? ? }? ? ? ? public void setTicket(String ticket) {? ? ? ? ? Ticket = ticket;? ? ? }? } import java.lang.annotation.ElementType;? import java.lang.annotation.Retention;? import java.lang.annotation.RetentionPolicy;? import java.lang.annotation.Target;? ? @Retention(RetentionPolicy.RUNTIME)? @Target({ ElementType.FIELD })? public @interface XStreamCDATA {? ? }? ```然后我們定義一個返回類根據(jù)對應的事件返回文本消息數(shù)據(jù)代碼如下:```import com.thoughtworks.xstream.annotations.XStreamAlias;? ? @XStreamAlias("xml")? public class OutputMessage {? ? ? ? @XStreamAlias("ToUserName")? ? ? @XStreamCDATA? ? ? private String ToUserName;? ? ? ? @XStreamAlias("FromUserName")? ? ? @XStreamCDATA? ? ? private String FromUserName;? ? ? ? @XStreamAlias("CreateTime")? ? ? private Long CreateTime;? ? ? ? @XStreamAlias("MsgType")? ? ? @XStreamCDATA? ? ? private String MsgType = "text";? ? ? ? private ImageMessage Image;? ? ? ? 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;? ? ? }? ? ? ? public ImageMessage getImage() {? ? ? ? ? return Image;? ? ? }? ? ? ? public void setImage(ImageMessage image) {? ? ? ? ? Image = image;? ? ? } }? ```最后將消息轉(zhuǎn)換給xml格式發(fā)送給用戶所以還需要一個xml轉(zhuǎn)換類代碼如下:```import com.thoughtworks.xstream.XStream;? import com.thoughtworks.xstream.annotations.XStreamAlias;? 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 java.io.Writer;? import java.lang.reflect.Field;? public class SerializeXmlUtil {? ? ? public static XStream createXstream() {? ? ? ? ? return new XStream(new XppDriver() {? ? ? ? ? ? ? @Override? ? ? ? ? ? ? public HierarchicalStreamWriter createWriter(Writer out) {? ? ? ? ? ? ? ? ? return new PrettyPrintWriter(out) {? ? ? ? ? ? ? ? ? ? ? boolean cdata = false;? ? ? ? ? ? ? ? ? ? ? Class? targetClass = null;? ? ? ? ? ? ? ? ? ? ? ? @Override? ? ? ? ? ? ? ? ? ? ? public void startNode(String name, @SuppressWarnings("rawtypes") Class clazz) {? ? ? ? ? ? ? ? ? ? ? ? ? super.startNode(name, clazz);? ? ? ? ? ? ? ? ? ? ? ? ? // 業(yè)務處理户侥,對于用XStreamCDATA標記的Field镀琉,需要加上CDATA標簽? ? ? ? ? ? ? ? ? ? ? ? ? if (!name.equals("xml")) {? ? ? ? ? ? ? ? ? ? ? ? ? ? ? cdata = needCDATA(targetClass, name);? ? ? ? ? ? ? ? ? ? ? ? ? } else {? ? ? ? ? ? ? ? ? ? ? ? ? ? ? targetClass = clazz;? ? ? ? ? ? ? ? ? ? ? ? ? }? ? ? ? ? ? ? ? ? ? ? }? ? ? ? ? ? ? ? ? ? ? ? @Override? ? ? ? ? ? ? ? ? ? ? protected void writeText(QuickWriter writer, String text) {? ? ? ? ? ? ? ? ? ? ? ? ? if (cdata) {? ? ? ? ? ? ? ? ? ? ? ? ? ? ? writer.write("");? ? ? ? ? ? ? ? ? ? ? ? ? } else {? ? ? ? ? ? ? ? ? ? ? ? ? ? ? writer.write(text);? ? ? ? ? ? ? ? ? ? ? ? ? }? ? ? ? ? ? ? ? ? ? ? }? ? ? ? ? ? ? ? ? };? ? ? ? ? ? ? }? ? ? ? ? });? ? ? }? ? ? ? private static boolean needCDATA(ClasstargetClass, String fieldAlias) {? ? ? ? ? boolean cdata = false;? ? ? ? ? // first, scan self? ? ? ? ? cdata = existsCDATA(targetClass, fieldAlias);? ? ? ? ? if (cdata)? ? ? ? ? ? ? return cdata;? ? ? ? ? // if cdata is false, scan supperClass until java.lang.Object? ? ? ? ? ClasssuperClass = targetClass.getSuperclass();? ? ? ? ? while (!superClass.equals(Object.class)) {? ? ? ? ? ? ? cdata = existsCDATA(superClass, fieldAlias);? ? ? ? ? ? ? if (cdata)? ? ? ? ? ? ? ? ? return cdata;? ? ? ? ? ? ? superClass = superClass.getClass().getSuperclass();? ? ? ? ? }? ? ? ? ? return false;? ? ? }? ? ? ? private static boolean existsCDATA(Classclazz, String fieldAlias) {? ? ? ? ? if ("MediaId".equals(fieldAlias)) {? ? ? ? ? ? ? return true; // 特例添加 morning99? ? ? ? ? }? ? ? ? ? // scan fields? ? ? ? ? Field[] fields = clazz.getDeclaredFields();? ? ? ? ? for (Field field : fields) {? ? ? ? ? ? ? // 1. exists XStreamCDATA? ? ? ? ? ? ? if (field.getAnnotation(XStreamCDATA.class) != null) {? ? ? ? ? ? ? ? ? XStreamAlias xStreamAlias = field.getAnnotation(XStreamAlias.class);? ? ? ? ? ? ? ? ? // 2. exists XStreamAlias? ? ? ? ? ? ? ? ? if (null != xStreamAlias) {? ? ? ? ? ? ? ? ? ? ? if (fieldAlias.equals(xStreamAlias.value()))// matched? ? ? ? ? ? ? ? ? ? ? ? ? return true;? ? ? ? ? ? ? ? ? } else {// not exists XStreamAlias? ? ? ? ? ? ? ? ? ? ? if (fieldAlias.equals(field.getName()))? ? ? ? ? ? ? ? ? ? ? ? ? return true;? ? ? ? ? ? ? ? ? }? ? ? ? ? ? ? }? ? ? ? ? }? ? ? ? ? return false;? ? ? }? ? }? ```需要第三方的xml? 轉(zhuǎn)換的jar? 支持這里我們引入? ```? 《dependency》? 《groupId〉om.thoughtworks.xstream《/groupId>? ? 《artifactId>xstream《/artifactId>? ? 《version>1.4.9《/version> 《/dependency> ```工具類弄好了接下來就是投入使用了。微信那邊采用的是post 請求所以我們在post中處理數(shù)據(jù)``` if (isGet) {? ? ? ? ? ? // 微信加密簽名? ? ? ? ? ? String signature = request.getParameter("signature");? ? ? ? ? ? // 時間戳? ? ? ? ? ? String timestamp = request.getParameter("timestamp");? ? ? ? ? ? // 隨機數(shù)? ? ? ? ? ? String nonce = request.getParameter("nonce");? ? ? ? ? ? // 隨機字符串? ? ? ? ? ? String echostr = request.getParameter("echostr");? ? ? ? ? ? // 通過檢驗signature對請求進行校驗蕊唐,若校驗成功則原樣返回echostr屋摔,表示接入成功,否則接入失敗? ? ? ? ? ? if (signature != null && CheckoutUtil.checkSignature(StringConfig.Wen_Code,signature, timestamp, nonce)) {? ? ? ? ? ? ? ? try {? ? ? ? ? ? ? ? ? ? print = response.getWriter();? ? ? ? ? ? ? ? ? ? print.write(echostr);? ? ? ? ? ? ? ? ? ? print.flush();? ? ? ? ? ? ? ? } catch (IOException e) {? ? ? ? ? ? ? ? ? ? e.printStackTrace();? ? ? ? ? ? ? ? }? ? ? ? ? ? }? ? ? ? }else {? ? ? ? try {? ? ? ? ? ? ? ? ? // 接收消息并返回消息? ? ? ? ? ? ? ? new AcceptMessage().acceptMessage(request, response);? ? ? ? ? ? ? } catch (IOException e) {? ? ? ? ? ? ? ? ? e.printStackTrace();? ? ? ? ? ? ? }? ? ? ? ? }```接下來就是acceptMessage登場的時間了替梨,我們先通過ServletInputStream 獲得流數(shù)據(jù)钓试,接下來使用xml工具類轉(zhuǎn)化成InputMessage 對象取得消息數(shù)據(jù)再根據(jù)消息數(shù)據(jù)處理返回 結(jié)果即可,據(jù)圖代碼如下所示:```import java.io.IOException;import java.util.Calendar;import java.util.Date;import javax.servlet.ServletInputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.thoughtworks.xstream.XStream;import com.wen.blog.dto.TLResult;import com.wen.blog.util.HandleTalk;import com.wen.blog.util.ResultMsg;public class AcceptMessage {? ? private Logger logger = LoggerFactory.getLogger(this.getClass());public void acceptMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {? ? ? ? ? // 處理接收消息? ? ? ? ? ServletInputStream in = request.getInputStream();? ? ? ? ? // 將POST流轉(zhuǎn)換為XStream對象? ? ? ? ? XStream xs = SerializeXmlUtil.createXstream();? ? ? ? ? xs.processAnnotations(InputMessage.class);? ? ? ? ? xs.processAnnotations(OutputMessage.class);? ? ? ? ? // 將指定節(jié)點下的xml節(jié)點數(shù)據(jù)映射為對象? ? ? ? ? xs.alias("xml", InputMessage.class);? ? ? ? ? // 將流轉(zhuǎn)換為字符串? ? ? ? ? StringBuilder xmlMsg = new StringBuilder();? ? ? ? ? byte[] b = new byte[4096];? ? ? ? ? for (int n; (n = in.read(b)) != -1;) {? ? ? ? ? ? ? xmlMsg.append(new String(b, 0, n, "UTF-8"));? ? ? ? ? }? ? ? ? ? // 將xml內(nèi)容轉(zhuǎn)換為InputMessage對象? ? ? ? ? InputMessage inputMsg = (InputMessage) xs.fromXML(xmlMsg.toString());? ? ? ? ? ? String servername = inputMsg.getToUserName();// 服務端? ? ? ? ? String custermname = inputMsg.getFromUserName();// 客戶端? ? ? ? ? long createTime = inputMsg.getCreateTime();// 接收時間? ? ? ? ? Long returnTime = Calendar.getInstance().getTimeInMillis() / 1000;// 返回時間? ? ? ? ? ? // 取得消息類型? ? ? ? ? String msgType = inputMsg.getMsgType();? ? ? ? ? // 根據(jù)消息類型獲取對應的消息內(nèi)容? ? ? ? ResultMsg msg= new HandleTalk().handleTalk(inputMsg.getContent());? ? ? ? TLResult tl=(TLResult) msg.getData();? ? ? ? logger.info("回答的內(nèi)容"+tl.text);? ? ? ? ? ? ? ? //String xmString = new String(tl.text.toString().getBytes("UTF-8"));? ? ? ? ? String xmString = tl.text;//new String(.toString().getBytes("UTF-8"));? ? ? ? ? ? ? //msgType.equals(MsgType.Text.toString())? ? ? ? if (tl.code==100000) {? ? ? ? ? ? ? // 文本消息? ? ? ? ? ? ? System.out.println("開發(fā)者微信號:" + inputMsg.getToUserName());? ? ? ? ? ? ? System.out.println("發(fā)送方帳號:" + inputMsg.getFromUserName());? ? ? ? ? ? ? System.out.println("消息創(chuàng)建時間:" + inputMsg.getCreateTime() + new Date(createTime * 1000l));? ? ? ? ? ? ? System.out.println("消息內(nèi)容:" + inputMsg.getContent());? ? ? ? ? ? ? System.out.println("消息Id:" + inputMsg.getMsgId());? ? ? ? ? ? ? System.out.println("消息類型:" + msgType);? ? ? ? ? ? ? StringBuffer str = new StringBuffer();? ? ? ? ? ? ? str.append("");? ? ? ? ? ? ? str.append("");? ? ? ? ? ? ? str.append("");? ? ? ? ? ? ? str.append("" + returnTime + "");? ? ? ? ? ? ? str.append("");? ? ? ? ? ? ? str.append("");? ? ? ? ? ? ? str.append("");? ? ? ? ? ? ? System.out.println(str.toString());? ? ? ? ? ? ? response.getWriter().write(str.toString());? ? ? ? ? }? else if(tl.code==200000){? ? ? ? ? OutputMessage outputMsg = new OutputMessage();? ? ? ? ? ? ? outputMsg.setFromUserName(servername);? ? ? ? ? ? ? outputMsg.setToUserName(custermname);? ? ? ? ? ? ? outputMsg.setCreateTime(returnTime);? ? ? ? ? ? ? outputMsg.setMsgType(msgType);? ? ? ? ? ? ? ImageMessage images = new ImageMessage();? ? ? ? ? ? ? images.setMediaId(inputMsg.getMediaId());? ? ? ? ? ? ? outputMsg.setImage(images);? ? ? ? ? ? ? System.out.println("xml轉(zhuǎn)換:/n" + xs.toXML(outputMsg));? ? ? ? ? ? ? response.getWriter().write(xs.toXML(outputMsg));? ? ? ? ? }? ? ? ? ? ? ? // 獲取并返回多圖片消息? ? ? ? ? /*if (msgType.equals(MsgType.Image.toString())) {? ? ? ? ? ? ? System.out.println("獲取多媒體信息");? ? ? ? ? ? ? System.out.println("多媒體文件id:" + inputMsg.getMediaId());? ? ? ? ? ? ? System.out.println("圖片鏈接:" + inputMsg.getPicUrl());? ? ? ? ? ? ? System.out.println("消息id副瀑,64位整型:" + inputMsg.getMsgId());? ? ? ? ? ? ? ? OutputMessage outputMsg = new OutputMessage();? ? ? ? ? ? ? outputMsg.setFromUserName(servername);? ? ? ? ? ? ? outputMsg.setToUserName(custermname);? ? ? ? ? ? ? outputMsg.setCreateTime(returnTime);? ? ? ? ? ? ? outputMsg.setMsgType(msgType);? ? ? ? ? ? ? ImageMessage images = new ImageMessage();? ? ? ? ? ? ? images.setMediaId(inputMsg.getMediaId());? ? ? ? ? ? ? outputMsg.setImage(images);? ? ? ? ? ? ? System.out.println("xml轉(zhuǎn)換:/n" + xs.toXML(outputMsg));? ? ? ? ? ? ? response.getWriter().write(xs.toXML(outputMsg));? ? ? ? ? ? }? */? ? }? }? ```
到此就能實現(xiàn)了亚侠,個人博客地址 www.haha174.top