我們專注:網(wǎng)站策劃設(shè)計、網(wǎng)絡(luò)多媒體傳播、網(wǎng)站優(yōu)化及網(wǎng)站營銷、品牌策略與設(shè)計、微信小程序開發(fā)以及微信公眾平臺開發(fā)
主營業(yè)務:網(wǎng)站建設(shè)、移動端微信小程序開發(fā)、小程序社區(qū)團購系統(tǒng)、VI設(shè)計、網(wǎng)絡(luò)運營、云產(chǎn)品·運維解決方案
您可以填寫右邊的表格,讓我們了解您的項目需求,這是一個良好的開始,我們將會盡快與您取得聯(lián)系。當然也歡迎您給我們寫信或是打電話,讓我們聽到您的聲音
地 址: 深圳市寶安區(qū)石巖街道光明路宏宇大廈4樓
電 話: 18312533681
微 信: 18312533681
郵 箱: etd@etding.com
網(wǎng) 址: https://www.etding.com http://www.bjswfwl.com.cn
快速提交您的需求 ↓
2020-06-12 14:42:361851
易通鼎下面就講解其核心部分——解析接收到的xml數(shù)據(jù),并以文本類消息為例,通過圖靈機器人api接口實現(xiàn)智能回復。
2.1 首先看一下整體流程處理代碼,包括:xml數(shù)據(jù)處理、調(diào)用圖靈api、封裝返回的xml數(shù)據(jù)。
package demo.process;
import java.util.Date;
import demo.entity.ReceiveXmlEntity;
/**
* 微信xml消息處理流程邏輯類
* @author pamchen-1
*
*/
public class WechatProcess {
/**
* 解析處理xml、獲取智能回復結(jié)果(通過圖靈機器人api接口)
* @param xml 接收到的微信數(shù)據(jù)
* @return 最終的解析結(jié)果(xml格式數(shù)據(jù))
*/
public String processWechatMag(String xml){
/** 解析xml數(shù)據(jù) */
ReceiveXmlEntity xmlEntity = new ReceiveXmlProcess().getMsgEntity(xml);
/** 以文本消息為例,調(diào)用圖靈機器人api接口,獲取回復內(nèi)容 */
String result = "";
if("text".endsWith(xmlEntity.getMsgType())){
result = new TulingApiProcess().getTulingResult(xmlEntity.getContent());
}
/** 此時,如果用戶輸入的是“你好”,在經(jīng)過上面的過程之后,result為“你也好”類似的內(nèi)容
* 因為最終回復給微信的也是xml格式的數(shù)據(jù),所有需要將其封裝為文本類型返回消息
* */
result = new FormatXmlProcess().formatXmlAnswer(xmlEntity.getFromUserName(), xmlEntity.getToUserName(), result);
return result;
}
}
2.2 解析接收到的xml數(shù)據(jù),此處有兩個類,ReceiveXmlEntity.java和ReceiveXmlProcess.java,通過反射的機制動態(tài)調(diào)用實體類中的set方法,可以避免很多重復的判斷,提高代碼效率,代碼如下:
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;
}
}
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;
// 將字符串轉(zhuǎn)化為XML文檔對象
Document document = DocumentHelper.parseText(strXml);
// 獲得文檔的根節(jié)點
Element root = document.getRootElement();
// 遍歷根節(jié)點下所有子節(jié)點
Iterator<?> iter = root.elementIterator();
// 遍歷所有結(jié)點
msg = new ReceiveXmlEntity();
//利用反射機制,調(diào)用set方法
//獲取該實體的元類型
Class<?> c = Class.forName("demo.entity.ReceiveXmlEntity");
msg = (ReceiveXmlEntity)c.newInstance();//創(chuàng)建這個實體的對象
while(iter.hasNext()){
Element ele = (Element)iter.next();
//獲取set方法中的參數(shù)字段(實體類的屬性)
Field field = c.getDeclaredField(ele.getName());
//獲取set方法,field.getType())獲取它的參數(shù)數(shù)據(jù)類型
Method method = c.getDeclaredMethod("set"+ele.getName(), field.getType());
//調(diào)用set方法
method.invoke(msg, ele.getText());
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("xml 格式異常: "+ strXml);
e.printStackTrace();
}
return msg;
}
}
2.3 調(diào)用圖靈機器人api接口,獲取智能回復內(nèi)容:
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;
/**
* 調(diào)用圖靈機器人api接口,獲取智能回復內(nèi)容
* @author pamchen-1
*
*/
public class TulingApiProcess {
/**
* 調(diào)用圖靈機器人api接口,獲取智能回復內(nèi)容,解析獲取自己所需結(jié)果
* @param content
* @return
*/
public String getTulingResult(String content){
/** 此處為圖靈api接口,參數(shù)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();
} //將參數(shù)轉(zhuǎn)為url編碼
/** 發(fā)送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 將結(jié)果封裝為微信規(guī)定的xml格式,并返回給1.1中創(chuàng)建的servlet接口。
package demo.process;
import java.util.Date;
/**
* 封裝最終的xml格式結(jié)果
* @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();
您好HELLO!
感謝您來到深圳網(wǎng)站建設(shè)公司,若您有合作意向,請您為我們留言或使用以下方式聯(lián)系我們,
我們將盡快給你回復,并為您提供真誠的設(shè)計服務,謝謝。
電話:0755- 27088176 18312533681
商務合作郵箱:kf@etding.cc
合作QQ: 120274683
深圳網(wǎng)站設(shè)計地址:寶安區(qū)石巖街道光明路宏宇大廈4樓
經(jīng)過十幾年的積累,易通鼎員工總數(shù)逾100人,擁有項目經(jīng)理、設(shè)計師、工程師30多人。易通鼎秉承"專業(yè)團隊、品質(zhì)服務" 的經(jīng)營理念,誠 信務實的服務了5000多家客戶, 成為300家集團、上市公司的長期合作伙伴。
相對傳統(tǒng)的深圳網(wǎng)站建設(shè)公司而言,易通鼎是互聯(lián)網(wǎng)中的網(wǎng)站品牌策劃精英,我們精于企業(yè)品牌與互聯(lián)網(wǎng)相結(jié)合的整體戰(zhàn)略服務。
我們始終認為,網(wǎng)站必須注入企業(yè)基因,真正使網(wǎng)站成為企業(yè)vi的一部分,讓整個網(wǎng)站品牌策劃體系變的深入而持久。