微信公衆平臺java開發詳解

說明:
本次的教程主要是對微信公衆平臺開發者模式的講解,網絡上很多類似文章,但很多都讓初學微信開發的人一頭霧水,所以總結自己的微信開發經驗,將微信開發的整個過程系統的列出,並對主要代碼進行講解分析,讓初學者儘快上手。

在閱讀本文之前,應對微信公衆平臺的官方開發文檔有所瞭解,知道接收和發送的都是xml格式的數據。另外,在做內容回覆時用到了圖靈機器人的api接口這是一個自然語言解析的開放平臺,可以幫我們解決整個微信開發過程中最困難的問題,此處不多講,下面會有其詳細的調用方式。


1.1 在登錄微信官方平臺之後,開啓開發者模式,此時需要我們填寫url和token,所謂url就是我們自己服務器的接口,用WechatServlet.java來實現,相關解釋已經在註釋中說明,代碼如下:

  1. package demo.servlet;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.InputStreamReader;  
  7. import java.io.OutputStream;  
  8.   
  9. import javax.servlet.ServletException;  
  10. import javax.servlet.http.HttpServlet;  
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13.   
  14. import demo.process.WechatProcess;  
  15. /** 
  16.  * 微信服務端收發消息接口 
  17.  *  
  18.  * @author pamchen-1 
  19.  *  
  20.  */  
  21. public class WechatServlet extends HttpServlet {  
  22.   
  23.     /** 
  24.      * The doGet method of the servlet. <br> 
  25.      *  
  26.      * This method is called when a form has its tag value method equals to get. 
  27.      *  
  28.      * @param request 
  29.      *            the request send by the client to the server 
  30.      * @param response 
  31.      *            the response send by the server to the client 
  32.      * @throws ServletException 
  33.      *             if an error occurred 
  34.      * @throws IOException 
  35.      *             if an error occurred 
  36.      */  
  37.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  38.             throws ServletException, IOException {  
  39.         request.setCharacterEncoding("UTF-8");  
  40.         response.setCharacterEncoding("UTF-8");  
  41.   
  42.         /** 讀取接收到的xml消息 */  
  43.         StringBuffer sb = new StringBuffer();  
  44.         InputStream is = request.getInputStream();  
  45.         InputStreamReader isr = new InputStreamReader(is, "UTF-8");  
  46.         BufferedReader br = new BufferedReader(isr);  
  47.         String s = "";  
  48.         while ((s = br.readLine()) != null) {  
  49.             sb.append(s);  
  50.         }  
  51.         String xml = sb.toString(); //次即爲接收到微信端發送過來的xml數據  
  52.   
  53.         String result = "";  
  54.         /** 判斷是否是微信接入激活驗證,只有首次接入驗證時纔會收到echostr參數,此時需要把它直接返回 */  
  55.         String echostr = request.getParameter("echostr");  
  56.         if (echostr != null && echostr.length() > 1) {  
  57.             result = echostr;  
  58.         } else {  
  59.             //正常的微信處理流程  
  60.             result = new WechatProcess().processWechatMag(xml);  
  61.         }  
  62.   
  63.         try {  
  64.             OutputStream os = response.getOutputStream();  
  65.             os.write(result.getBytes("UTF-8"));  
  66.             os.flush();  
  67.             os.close();  
  68.         } catch (Exception e) {  
  69.             e.printStackTrace();  
  70.         }  
  71.     }  
  72.   
  73.     /** 
  74.      * The doPost method of the servlet. <br> 
  75.      *  
  76.      * This method is called when a form has its tag value method equals to 
  77.      * post. 
  78.      *  
  79.      * @param request 
  80.      *            the request send by the client to the server 
  81.      * @param response 
  82.      *            the response send by the server to the client 
  83.      * @throws ServletException 
  84.      *             if an error occurred 
  85.      * @throws IOException 
  86.      *             if an error occurred 
  87.      */  
  88.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  89.             throws ServletException, IOException {  
  90.         doGet(request, response);  
  91.     }  
  92.   
  93. }  
package demo.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

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

import demo.process.WechatProcess;
/**
 * 微信服務端收發消息接口
 * 
 * @author pamchen-1
 * 
 */
public class WechatServlet extends HttpServlet {

	/**
	 * 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 {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		/** 讀取接收到的xml消息 */
		StringBuffer sb = new StringBuffer();
		InputStream is = request.getInputStream();
		InputStreamReader isr = new InputStreamReader(is, "UTF-8");
		BufferedReader br = new BufferedReader(isr);
		String s = "";
		while ((s = br.readLine()) != null) {
			sb.append(s);
		}
		String xml = sb.toString();	//次即爲接收到微信端發送過來的xml數據

		String result = "";
		/** 判斷是否是微信接入激活驗證,只有首次接入驗證時纔會收到echostr參數,此時需要把它直接返回 */
		String echostr = request.getParameter("echostr");
		if (echostr != null && echostr.length() > 1) {
			result = echostr;
		} else {
			//正常的微信處理流程
			result = new WechatProcess().processWechatMag(xml);
		}

		try {
			OutputStream os = response.getOutputStream();
			os.write(result.getBytes("UTF-8"));
			os.flush();
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 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 {
		doGet(request, response);
	}

}

1.2 相應的web.xml配置信息如下,在生成WechatServlet.java的同時,可自動生成web.xml中的配置。前面所提到的url處可以填寫例如:http;//服務器地址/項目名/wechat.do

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.   <servlet>  
  8.     <description>This is the description of my J2EE component</description>  
  9.     <display-name>This is the display name of my J2EE component</display-name>  
  10.     <servlet-name>WechatServlet</servlet-name>  
  11.     <servlet-class>demo.servlet.WechatServlet</servlet-class>  
  12.   </servlet>  
  13.   
  14.   <servlet-mapping>  
  15.     <servlet-name>WechatServlet</servlet-name>  
  16.     <url-pattern>/wechat.do</url-pattern>  
  17.   </servlet-mapping>  
  18.   <welcome-file-list>  
  19.     <welcome-file>index.jsp</welcome-file>  
  20.   </welcome-file-list>  
  21. </web-app>  
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>WechatServlet</servlet-name>
    <servlet-class>demo.servlet.WechatServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>WechatServlet</servlet-name>
    <url-pattern>/wechat.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

1.3 通過以上代碼,我們已經實現了微信公衆平臺開發的框架,即開通開發者模式併成功接入、接收消息和發送消息這三個步驟。


下面就講解其核心部分——解析接收到的xml數據,並以文本類消息爲例,通過圖靈機器人api接口實現智能回覆。


2.1 首先看一下整體流程處理代碼,包括:xml數據處理、調用圖靈api、封裝返回的xml數據。
  1. package demo.process;  
  2.   
  3. import java.util.Date;  
  4.   
  5. import demo.entity.ReceiveXmlEntity;  
  6.   
  7. /** 
  8.  * 微信xml消息處理流程邏輯類 
  9.  * @author pamchen-1 
  10.  * 
  11.  */  
  12. public class WechatProcess {  
  13.     /** 
  14.      * 解析處理xml、獲取智能回覆結果(通過圖靈機器人api接口) 
  15.      * @param xml 接收到的微信數據 
  16.      * @return  最終的解析結果(xml格式數據) 
  17.      */  
  18.     public String processWechatMag(String xml){  
  19.         /** 解析xml數據 */  
  20.         ReceiveXmlEntity xmlEntity = new ReceiveXmlProcess().getMsgEntity(xml);  
  21.           
  22.         /** 以文本消息爲例,調用圖靈機器人api接口,獲取回覆內容 */  
  23.         String result = "";  
  24.         if("text".endsWith(xmlEntity.getMsgType())){  
  25.             result = new TulingApiProcess().getTulingResult(xmlEntity.getContent());  
  26.         }  
  27.           
  28.         /** 此時,如果用戶輸入的是“你好”,在經過上面的過程之後,result爲“你也好”類似的內容  
  29.          *  因爲最終回覆給微信的也是xml格式的數據,所有需要將其封裝爲文本類型返回消息 
  30.          * */  
  31.         result = new FormatXmlProcess().formatXmlAnswer(xmlEntity.getFromUserName(), xmlEntity.getToUserName(), result);  
  32.           
  33.         return result;  
  34.     }  
  35. }  
package demo.process;

import java.util.Date;

import demo.entity.ReceiveXmlEntity;

/**
 * 微信xml消息處理流程邏輯類
 * @author pamchen-1
 *
 */
public class WechatProcess {
	/**
	 * 解析處理xml、獲取智能回覆結果(通過圖靈機器人api接口)
	 * @param xml 接收到的微信數據
	 * @return	最終的解析結果(xml格式數據)
	 */
	public String processWechatMag(String xml){
		/** 解析xml數據 */
		ReceiveXmlEntity xmlEntity = new ReceiveXmlProcess().getMsgEntity(xml);
		
		/** 以文本消息爲例,調用圖靈機器人api接口,獲取回覆內容 */
		String result = "";
		if("text".endsWith(xmlEntity.getMsgType())){
			result = new TulingApiProcess().getTulingResult(xmlEntity.getContent());
		}
		
		/** 此時,如果用戶輸入的是“你好”,在經過上面的過程之後,result爲“你也好”類似的內容 
		 *  因爲最終回覆給微信的也是xml格式的數據,所有需要將其封裝爲文本類型返回消息
		 * */
		result = new FormatXmlProcess().formatXmlAnswer(xmlEntity.getFromUserName(), xmlEntity.getToUserName(), result);
		
		return result;
	}
}

2.2 解析接收到的xml數據,此處有兩個類,ReceiveXmlEntity.java和ReceiveXmlProcess.java,通過反射的機制動態調用實體類中的set方法,可以避免很多重複的判斷,提高代碼效率,代碼如下:

  1. package demo.entity;  
  2. /** 
  3.  * 接收到的微信xml實體類 
  4.  * @author pamchen-1 
  5.  * 
  6.  */  
  7. public class ReceiveXmlEntity {  
  8.     private String ToUserName="";  
  9.     private String FromUserName="";  
  10.     private String CreateTime="";  
  11.     private String MsgType="";  
  12.     private String MsgId="";  
  13.     private String Event="";  
  14.     private String EventKey="";  
  15.     private String Ticket="";  
  16.     private String Latitude="";  
  17.     private String Longitude="";  
  18.     private String Precision="";  
  19.     private String PicUrl="";  
  20.     private String MediaId="";  
  21.     private String Title="";  
  22.     private String Description="";  
  23.     private String Url="";  
  24.     private String Location_X="";  
  25.     private String Location_Y="";  
  26.     private String Scale="";  
  27.     private String Label="";  
  28.     private String Content="";  
  29.     private String Format="";  
  30.     private String Recognition="";  
  31.       
  32.     public String getRecognition() {  
  33.         return Recognition;  
  34.     }  
  35.     public void setRecognition(String recognition) {  
  36.         Recognition = recognition;  
  37.     }  
  38.     public String getFormat() {  
  39.         return Format;  
  40.     }  
  41.     public void setFormat(String format) {  
  42.         Format = format;  
  43.     }  
  44.     public String getContent() {  
  45.         return Content;  
  46.     }  
  47.     public void setContent(String content) {  
  48.         Content = content;  
  49.     }  
  50.     public String getLocation_X() {  
  51.         return Location_X;  
  52.     }  
  53.     public void setLocation_X(String locationX) {  
  54.         Location_X = locationX;  
  55.     }  
  56.     public String getLocation_Y() {  
  57.         return Location_Y;  
  58.     }  
  59.     public void setLocation_Y(String locationY) {  
  60.         Location_Y = locationY;  
  61.     }  
  62.     public String getScale() {  
  63.         return Scale;  
  64.     }  
  65.     public void setScale(String scale) {  
  66.         Scale = scale;  
  67.     }  
  68.     public String getLabel() {  
  69.         return Label;  
  70.     }  
  71.     public void setLabel(String label) {  
  72.         Label = label;  
  73.     }  
  74.     public String getTitle() {  
  75.         return Title;  
  76.     }  
  77.     public void setTitle(String title) {  
  78.         Title = title;  
  79.     }  
  80.     public String getDescription() {  
  81.         return Description;  
  82.     }  
  83.     public void setDescription(String description) {  
  84.         Description = description;  
  85.     }  
  86.     public String getUrl() {  
  87.         return Url;  
  88.     }  
  89.     public void setUrl(String url) {  
  90.         Url = url;  
  91.     }  
  92.     public String getPicUrl() {  
  93.         return PicUrl;  
  94.     }  
  95.     public void setPicUrl(String picUrl) {  
  96.         PicUrl = picUrl;  
  97.     }  
  98.     public String getMediaId() {  
  99.         return MediaId;  
  100.     }  
  101.     public void setMediaId(String mediaId) {  
  102.         MediaId = mediaId;  
  103.     }  
  104.     public String getEventKey() {  
  105.         return EventKey;  
  106.     }  
  107.     public void setEventKey(String eventKey) {  
  108.         EventKey = eventKey;  
  109.     }  
  110.     public String getTicket() {  
  111.         return Ticket;  
  112.     }  
  113.     public void setTicket(String ticket) {  
  114.         Ticket = ticket;  
  115.     }  
  116.     public String getLatitude() {  
  117.         return Latitude;  
  118.     }  
  119.     public void setLatitude(String latitude) {  
  120.         Latitude = latitude;  
  121.     }  
  122.     public String getLongitude() {  
  123.         return Longitude;  
  124.     }  
  125.     public void setLongitude(String longitude) {  
  126.         Longitude = longitude;  
  127.     }  
  128.     public String getPrecision() {  
  129.         return Precision;  
  130.     }  
  131.     public void setPrecision(String precision) {  
  132.         Precision = precision;  
  133.     }  
  134.     public String getEvent() {  
  135.         return Event;  
  136.     }  
  137.     public void setEvent(String event) {  
  138.         Event = event;  
  139.     }  
  140.     public String getMsgId() {  
  141.         return MsgId;  
  142.     }  
  143.     public void setMsgId(String msgId) {  
  144.         MsgId = msgId;  
  145.     }  
  146.     public String getToUserName() {  
  147.         return ToUserName;  
  148.     }  
  149.     public void setToUserName(String toUserName) {  
  150.         ToUserName = toUserName;  
  151.     }  
  152.     public String getFromUserName() {  
  153.         return FromUserName;  
  154.     }  
  155.     public void setFromUserName(String fromUserName) {  
  156.         FromUserName = fromUserName;  
  157.     }  
  158.     public String getCreateTime() {  
  159.         return CreateTime;  
  160.     }  
  161.     public void setCreateTime(String createTime) {  
  162.         CreateTime = createTime;  
  163.     }  
  164.     public String getMsgType() {  
  165.         return MsgType;  
  166.     }  
  167.     public void setMsgType(String msgType) {  
  168.         MsgType = msgType;  
  169.     }  
  170. }  
package demo.entity;
/**
 * 接收到的微信xml實體類
 * @author pamchen-1
 *
 */
public class ReceiveXmlEntity {
	private String ToUserName="";
	private String FromUserName="";
	private String CreateTime="";
	private String MsgType="";
	private String MsgId="";
	private String Event="";
	private String EventKey="";
	private String Ticket="";
	private String Latitude="";
	private String Longitude="";
	private String Precision="";
	private String PicUrl="";
	private String MediaId="";
	private String Title="";
	private String Description="";
	private String Url="";
	private String Location_X="";
	private String Location_Y="";
	private String Scale="";
	private String Label="";
	private String Content="";
	private String Format="";
	private String Recognition="";
	
	public String getRecognition() {
		return Recognition;
	}
	public void setRecognition(String recognition) {
		Recognition = recognition;
	}
	public String getFormat() {
		return Format;
	}
	public void setFormat(String format) {
		Format = format;
	}
	public String getContent() {
		return Content;
	}
	public void setContent(String content) {
		Content = content;
	}
	public String getLocation_X() {
		return Location_X;
	}
	public void setLocation_X(String locationX) {
		Location_X = locationX;
	}
	public String getLocation_Y() {
		return Location_Y;
	}
	public void setLocation_Y(String locationY) {
		Location_Y = locationY;
	}
	public String getScale() {
		return Scale;
	}
	public void setScale(String 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 getPicUrl() {
		return PicUrl;
	}
	public void setPicUrl(String picUrl) {
		PicUrl = picUrl;
	}
	public String getMediaId() {
		return MediaId;
	}
	public void setMediaId(String mediaId) {
		MediaId = mediaId;
	}
	public String getEventKey() {
		return EventKey;
	}
	public void setEventKey(String eventKey) {
		EventKey = eventKey;
	}
	public String getTicket() {
		return Ticket;
	}
	public void setTicket(String ticket) {
		Ticket = ticket;
	}
	public String getLatitude() {
		return Latitude;
	}
	public void setLatitude(String latitude) {
		Latitude = latitude;
	}
	public String getLongitude() {
		return Longitude;
	}
	public void setLongitude(String longitude) {
		Longitude = longitude;
	}
	public String getPrecision() {
		return Precision;
	}
	public void setPrecision(String precision) {
		Precision = precision;
	}
	public String getEvent() {
		return Event;
	}
	public void setEvent(String event) {
		Event = event;
	}
	public String getMsgId() {
		return MsgId;
	}
	public void setMsgId(String msgId) {
		MsgId = msgId;
	}
	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 String getCreateTime() {
		return CreateTime;
	}
	public void setCreateTime(String createTime) {
		CreateTime = createTime;
	}
	public String getMsgType() {
		return MsgType;
	}
	public void setMsgType(String msgType) {
		MsgType = msgType;
	}
}

  1. package demo.process;  
  2.   
  3. import java.lang.reflect.Field;  
  4. import java.lang.reflect.Method;  
  5. import java.util.Iterator;  
  6. import org.dom4j.Document;  
  7. import org.dom4j.DocumentHelper;  
  8. import org.dom4j.Element;  
  9.   
  10. import demo.entity.ReceiveXmlEntity;  
  11. /** 
  12.  * 解析接收到的微信xml,返回消息對象 
  13.  * @author pamchen-1 
  14.  * 
  15.  */  
  16. public class ReceiveXmlProcess {  
  17.     /** 
  18.      * 解析微信xml消息 
  19.      * @param strXml 
  20.      * @return 
  21.      */  
  22.     public ReceiveXmlEntity getMsgEntity(String strXml){  
  23.         ReceiveXmlEntity msg = null;  
  24.         try {  
  25.             if (strXml.length() <= 0 || strXml == null)  
  26.                 return null;  
  27.                
  28.             // 將字符串轉化爲XML文檔對象  
  29.             Document document = DocumentHelper.parseText(strXml);  
  30.             // 獲得文檔的根節點  
  31.             Element root = document.getRootElement();  
  32.             // 遍歷根節點下所有子節點  
  33.             Iterator<?> iter = root.elementIterator();  
  34.               
  35.             // 遍歷所有結點  
  36.             msg = new ReceiveXmlEntity();  
  37.             //利用反射機制,調用set方法  
  38.             //獲取該實體的元類型  
  39.             Class<?> c = Class.forName("demo.entity.ReceiveXmlEntity");  
  40.             msg = (ReceiveXmlEntity)c.newInstance();//創建這個實體的對象  
  41.               
  42.             while(iter.hasNext()){  
  43.                 Element ele = (Element)iter.next();  
  44.                 //獲取set方法中的參數字段(實體類的屬性)  
  45.                 Field field = c.getDeclaredField(ele.getName());  
  46.                 //獲取set方法,field.getType())獲取它的參數數據類型  
  47.                 Method method = c.getDeclaredMethod("set"+ele.getName(), field.getType());  
  48.                 //調用set方法  
  49.                 method.invoke(msg, ele.getText());  
  50.             }  
  51.         } catch (Exception e) {  
  52.             // TODO: handle exception  
  53.             System.out.println("xml 格式異常: "+ strXml);  
  54.             e.printStackTrace();  
  55.         }  
  56.         return msg;  
  57.     }  
  58. }  
package demo.process;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import demo.entity.ReceiveXmlEntity;
/**
 * 解析接收到的微信xml,返回消息對象
 * @author pamchen-1
 *
 */
public class ReceiveXmlProcess {
	/**
	 * 解析微信xml消息
	 * @param strXml
	 * @return
	 */
	public ReceiveXmlEntity getMsgEntity(String strXml){
		ReceiveXmlEntity msg = null;
		try {
			if (strXml.length() <= 0 || strXml == null)
				return null;
			 
			// 將字符串轉化爲XML文檔對象
			Document document = DocumentHelper.parseText(strXml);
			// 獲得文檔的根節點
			Element root = document.getRootElement();
			// 遍歷根節點下所有子節點
			Iterator<?> iter = root.elementIterator();
			
			// 遍歷所有結點
			msg = new ReceiveXmlEntity();
			//利用反射機制,調用set方法
			//獲取該實體的元類型
			Class<?> c = Class.forName("demo.entity.ReceiveXmlEntity");
			msg = (ReceiveXmlEntity)c.newInstance();//創建這個實體的對象
			
			while(iter.hasNext()){
				Element ele = (Element)iter.next();
				//獲取set方法中的參數字段(實體類的屬性)
				Field field = c.getDeclaredField(ele.getName());
				//獲取set方法,field.getType())獲取它的參數數據類型
				Method method = c.getDeclaredMethod("set"+ele.getName(), field.getType());
				//調用set方法
				method.invoke(msg, ele.getText());
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("xml 格式異常: "+ strXml);
			e.printStackTrace();
		}
		return msg;
	}
}

2.3 調用圖靈機器人api接口,獲取智能回覆內容

  1. package demo.process;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.UnsupportedEncodingException;  
  5. import java.net.URLEncoder;  
  6.   
  7. import org.apache.http.HttpResponse;  
  8. import org.apache.http.client.ClientProtocolException;  
  9. import org.apache.http.client.methods.HttpGet;  
  10. import org.apache.http.impl.client.HttpClients;  
  11. import org.apache.http.util.EntityUtils;  
  12. import org.json.JSONException;  
  13. import org.json.JSONObject;  
  14.   
  15. /** 
  16.  * 調用圖靈機器人api接口,獲取智能回覆內容 
  17.  * @author pamchen-1 
  18.  * 
  19.  */  
  20. public class TulingApiProcess {  
  21.     /** 
  22.      * 調用圖靈機器人api接口,獲取智能回覆內容,解析獲取自己所需結果 
  23.      * @param content 
  24.      * @return 
  25.      */  
  26.     public String getTulingResult(String content){  
  27.         /** 此處爲圖靈api接口,參數key需要自己去註冊申請,先以11111111代替 */  
  28.         String apiUrl = "http://www.tuling123.com/openapi/api?key=11111111&info=";  
  29.         String param = "";  
  30.         try {  
  31.             param = apiUrl+URLEncoder.encode(content,"utf-8");  
  32.         } catch (UnsupportedEncodingException e1) {  
  33.             // TODO Auto-generated catch block  
  34.             e1.printStackTrace();  
  35.         } //將參數轉爲url編碼  
  36.           
  37.         /** 發送httpget請求 */  
  38.         HttpGet request = new HttpGet(param);  
  39.         String result = "";  
  40.         try {  
  41.             HttpResponse response = HttpClients.createDefault().execute(request);  
  42.             if(response.getStatusLine().getStatusCode()==200){  
  43.                 result = EntityUtils.toString(response.getEntity());  
  44.             }  
  45.         } catch (ClientProtocolException e) {  
  46.             e.printStackTrace();  
  47.         } catch (IOException e) {  
  48.             e.printStackTrace();  
  49.         }  
  50.         /** 請求失敗處理 */  
  51.         if(null==result){  
  52.             return "對不起,你說的話真是太高深了……";  
  53.         }  
  54.           
  55.         try {  
  56.             JSONObject json = new JSONObject(result);  
  57.             //以code=100000爲例,參考圖靈機器人api文檔  
  58.             if(100000==json.getInt("code")){  
  59.                 result = json.getString("text");  
  60.             }  
  61.         } catch (JSONException e) {  
  62.             // TODO Auto-generated catch block  
  63.             e.printStackTrace();  
  64.         }  
  65.         return result;  
  66.     }  
  67. }  
package demo.process;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 調用圖靈機器人api接口,獲取智能回覆內容
 * @author pamchen-1
 *
 */
public class TulingApiProcess {
	/**
	 * 調用圖靈機器人api接口,獲取智能回覆內容,解析獲取自己所需結果
	 * @param content
	 * @return
	 */
	public String getTulingResult(String content){
		/** 此處爲圖靈api接口,參數key需要自己去註冊申請,先以11111111代替 */
		String apiUrl = "http://www.tuling123.com/openapi/api?key=11111111&info=";
		String param = "";
		try {
			param = apiUrl+URLEncoder.encode(content,"utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} //將參數轉爲url編碼
		
		/** 發送httpget請求 */
		HttpGet request = new HttpGet(param);
		String result = "";
		try {
			HttpResponse response = HttpClients.createDefault().execute(request);
			if(response.getStatusLine().getStatusCode()==200){
				result = EntityUtils.toString(response.getEntity());
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		/** 請求失敗處理 */
		if(null==result){
			return "對不起,你說的話真是太高深了……";
		}
		
		try {
			JSONObject json = new JSONObject(result);
			//以code=100000爲例,參考圖靈機器人api文檔
			if(100000==json.getInt("code")){
				result = json.getString("text");
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
}

2.4 將結果封裝爲微信規定的xml格式,並返回給1.1中創建的servlet接口。

  1. package demo.process;  
  2.   
  3. import java.util.Date;  
  4. /** 
  5.  * 封裝最終的xml格式結果 
  6.  * @author pamchen-1 
  7.  * 
  8.  */  
  9. public class FormatXmlProcess {  
  10.     /** 
  11.      * 封裝文字類的返回消息 
  12.      * @param to 
  13.      * @param from 
  14.      * @param content 
  15.      * @return 
  16.      */  
  17.     public String formatXmlAnswer(String to, String from, String content) {  
  18.         StringBuffer sb = new StringBuffer();  
  19.         Date date = new Date();  
  20.         sb.append("<xml><ToUserName><![CDATA[");  
  21.         sb.append(to);  
  22.         sb.append("]]></ToUserName><FromUserName><![CDATA[");  
  23.         sb.append(from);  
  24.         sb.append("]]></FromUserName><CreateTime>");  
  25.         sb.append(date.getTime());  
  26.         sb.append("</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[");  
  27.         sb.append(content);  
  28.         sb.append("]]></Content><FuncFlag>0</FuncFlag></xml>");  
  29.         return sb.toString();  
  30.     }  
  31. }  
package demo.process;

import java.util.Date;
/**
 * 封裝最終的xml格式結果
 * @author pamchen-1
 *
 */
public class FormatXmlProcess {
	/**
	 * 封裝文字類的返回消息
	 * @param to
	 * @param from
	 * @param content
	 * @return
	 */
	public String formatXmlAnswer(String to, String from, String content) {
		StringBuffer sb = new StringBuffer();
		Date date = new Date();
		sb.append("<xml><ToUserName><![CDATA[");
		sb.append(to);
		sb.append("]]></ToUserName><FromUserName><![CDATA[");
		sb.append(from);
		sb.append("]]></FromUserName><CreateTime>");
		sb.append(date.getTime());
		sb.append("</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[");
		sb.append(content);
		sb.append("]]></Content><FuncFlag>0</FuncFlag></xml>");
		return sb.toString();
	}
}

總結,以上便是微信公衆平臺開發的全部流程,整體來看並不複雜,要非常感謝圖靈機器人提供的api接口,幫我們解決了智能回覆這一高難度問題。其他類型的消息處理與示例中類似,有興趣的開發者可以聯繫我進行交流學習,希望本文對大家有所幫助。

原文地址:http://blog.csdn.net/pamchen/article/details/38718947

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章