這個(gè)聊天機(jī)器人有點(diǎn)像前段時(shí)間很火的一個(gè)安卓應(yīng)用——小黃雞


應(yīng)用的實(shí)現(xiàn)其實(shí)很簡(jiǎn)單,網(wǎng)上有許多關(guān)于智能機(jī)器人聊天的接口,我們只需要去調(diào)用對(duì)應(yīng)的接口,遵守它的API開發(fā)規(guī)范,就可以獲取到我們想要的信息
這里我使用的接口是——圖靈機(jī)器人(http://www.tuling123.com/openapi/)
這個(gè)接口給我們返回的是Json字符串,我們只需要對(duì)它進(jìn)行Json字符串解析,就可以實(shí)現(xiàn)這個(gè)應(yīng)用。
開發(fā)步驟:
首先我們需要到這個(gè)圖靈機(jī)器人的官網(wǎng)去注冊(cè)一個(gè)賬號(hào),他會(huì)給我們一個(gè)唯一Key,通過這個(gè)Key和對(duì)應(yīng)的API開發(fā)規(guī)范,我們就可以進(jìn)行開發(fā)了。

然后在這個(gè)(http://www.tuling123.com/openapi/cloud/access_api.jsp)網(wǎng)址里可以找到相關(guān)的開發(fā)介紹
比如:請(qǐng)求方式,參數(shù),返回參數(shù),包括開發(fā)范例,一些返回的編碼等信息


這里是官方提供的一個(gè)調(diào)用小案例(java),這里我也順帶貼一下
1 /** 調(diào)用圖靈機(jī)器人平臺(tái)接口 2 * 需要導(dǎo)入的包:commons-logging-1.0.4.jar、 httpclient-4.3.1.jar、httpcore-4.3.jar 3 */ 4 public static void main(String[] args) throws IOException { 5 6 String INFO = URLEncoder.encode("北京今日天氣", "utf-8"); 7 String requesturl = "http://www.tuling123.com/openapi/api?key= 注冊(cè)激活返回的Apikey&info="+INFO; 8 HttpGet request = new HttpGet(requesturl); 9 HttPResponse response = HttpClients.createDefault().execute(request); 10 11 //200即正確的返回碼 12 if(response.getStatusLine().getStatusCode()==200){ 13 String result = EntityUtils.toString(response.getEntity()); 14 System.out.println("返回結(jié)果:"+result); 15 } 16 }好了,接下來開始實(shí)戰(zhàn)吧,這個(gè)應(yīng)用我打算寫成兩篇文章
第一篇講下關(guān)于如何調(diào)用接口,從網(wǎng)上獲取數(shù)據(jù),包括解析Json字符串
第二篇會(huì)把這些獲取的數(shù)據(jù)嵌入到安卓應(yīng)用
首先,先寫一個(gè)工具類,這個(gè)工具類是用來獲取用戶輸入的信息并返回服務(wù)器提供的數(shù)據(jù)的
這里面用到了一個(gè)第三方提供的JAR包,Gson它是谷歌提供給我們用來使Json數(shù)據(jù)序列化和反序列化的
關(guān)于Gson的使用我之前寫過一篇筆記,不熟悉的朋友可以看看:Gson簡(jiǎn)要使用筆記(http://m.survivalescaperooms.com/lichenwei/p/3987429.html)
代碼如下:具體看注釋
1 package com.example.utils; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.UnsupportedEncodingException; 7 import java.net.HttpURLConnection; 8 import java.net.MalformedURLException; 9 import java.net.URLEncoder; 10 import java.util.Date; 11 12 import android.util.Log; 13 14 import com.example.pojo.Message; 15 import com.example.pojo.Message.Type; 16 import com.example.pojo.Result; 17 import com.google.gson.Gson; 18 19 /** 20 * 21 * 獲取信息幫助類 傳入用戶輸入的字符,給出相對(duì)應(yīng)的信息 22 * 23 */ 24 public class GetDataUtils { 25 26 private static final String API_KEY = "這里填寫官方提供的KEY";// 申請(qǐng)的API_KEY值 27 private static final String URL = "http://www.tuling123.com/openapi/api";// 接口請(qǐng)求地址 28 29 public String getChat(String msg) {//這個(gè)方法是獲取服務(wù)端返回回來的Json數(shù)據(jù),msg為用戶輸入的信息 30 String result = "";// 存放服務(wù)器返回信息的變量 31 InputStream inputStream = null; 32 ByteArrayOutputStream outputStream = null; 33 try { 34 // 進(jìn)行資源請(qǐng)求 35 java.net.URL url = new java.net.URL(getMsgUrl(msg)); 36 HttpURLConnection httpURLConnection = (HttpURLConnection) url 37 .openConnection();// 打開資源連接 38 39 // HttpURLConnection參數(shù)設(shè)定 40 httpURLConnection.setReadTimeout(5 * 1000); 41 httpURLConnection.setConnectTimeout(5 * 1000); 42 httpURLConnection.setRequestMethod("GET"); 43 44 inputStream = httpURLConnection.getInputStream();// 獲取一個(gè)輸入流接收服務(wù)端返回的信息 45 int len = -1; 46 byte[] bs = new byte[124];// 用來接收輸入流的字節(jié)數(shù)組 47 outputStream = new ByteArrayOutputStream();// 用一個(gè)輸出流來輸出剛獲取的輸入流所得到的信息 48 49 while ((len = inputStream.read(bs)) != -1) {// 從輸入流中讀取一定數(shù)量的字節(jié),并將其存儲(chǔ)在緩沖區(qū)數(shù)組 50 // bs 中 51 outputStream.write(bs, 0, len);// 往輸入流寫入 52 } 53 outputStream.flush();// 清除緩沖區(qū) 54 result = new String(outputStream.toByteArray());// 轉(zhuǎn)換成字符串 55 } catch (MalformedURLException e) { 56 e.printStackTrace(); 57 } catch (IOException e) { 58 e.printStackTrace(); 59 } finally { 60 // 關(guān)閉相關(guān)資源 61 if (inputStream != null) { 62 try { 63 inputStream.close(); 64 } catch (IOException e) { 65 e.printStackTrace(); 66 } 67 } 68 if (outputStream != null) { 69 try { 70 outputStream.close(); 71 } catch (IOException e) { 72 e.printStackTrace(); 73 } 74 } 75 } 76 Log.i("tuzi", "result:" + result);//打印測(cè)試日志 77 return result; 78 } 79 80 private String getMsgUrl(String msg) throws UnsupportedEncodingException { 81 String path = ""; 82 String info = URLEncoder.encode(msg, "UTF-8");// 轉(zhuǎn)換url編碼 83 path = URL + "?key=" + API_KEY + "&info=" + msg; 84 return path; 85 } 86 87 public Message getInfo(String msg){ 88 Message message=new Message(); 89 Gson gson=new Gson(); 90 try { 91 Result result=gson.fromJson(getChat(msg), Result.class);//獲取到服務(wù)器返回的json并轉(zhuǎn)換為Result對(duì)象,Result對(duì)象可能不存在,會(huì)出現(xiàn)異常 92 message.setMsg(result.getText());//message可能為空,需要捕獲異常 93 } catch (Exception e) { 94 //可能服務(wù)器沒有返回正常數(shù)據(jù),也就存在著空白內(nèi)容,需要捕獲異常 95 message.setMsg("服務(wù)器繁忙,請(qǐng)稍后再試"); 96 } 97 message.setTime(new Date()); 98 message.setType(Type.INCOME); 99 return message;100 }101 102 }下面這2個(gè)是實(shí)體類,根據(jù)官網(wǎng)提供的示例,返回的Json字符串里包含:code狀態(tài)碼,text文本內(nèi)容
1 package com.example.pojo; 2 /** 3 * 4 * 用來映射返回Json字符串 5 * 6 */ 7 public class Result { 8 9 private String code;10 private String text;11 12 public String getCode() {13 return code;14 }15 public void setCode(String code) {16 this.code = code;17 }18 public String getText() {19 return text;20 }21 public void setText(String text) {22 this.text = text;23 }24 25 26 27 } 1 package com.example.pojo; 2 3 import java.util.Date; 4 5 public class Message { 6 7 8 private String name; 9 private String msg;10 private Date time;11 private Type type;12 13 public enum Type{//類型枚舉,發(fā)送,接收14 INCOME,OUTCOME15 }16 public String getName() {17 return name;18 }19 20 public void setName(String name) {21 this.name = name;22 }23 24 public String getMsg() {25 return msg;26 }27 28 public void setMsg(String msg) {29 this.msg = msg;30 }31 32 public Date getTime() {33 return time;34 }35 36 public void setTime(Date time) {37 this.time = time;38 }39 40 public Type getType() {41 return type;42 }43 44 public void setType(Type type) {45 this.type = type;46 }47 48 49 50 }編寫個(gè)測(cè)試類
1 package com.example.test; 2 3 import android.test.AndroidTestCase; 4 import android.util.Log; 5 6 import com.example.pojo.Message; 7 import com.example.utils.GetDataUtils; 8 9 public class GetDataUtilsTest extends AndroidTestCase {10 11 public void test(){12 GetDataUtils dataUtils=new GetDataUtils();13 Message message=dataUtils.getInfo("你好");14 Message message1=dataUtils.getInfo("你是誰(shuí)");15 Message message2=dataUtils.getInfo("你知道JAVA是什么嗎");16 Message message3=dataUtils.getInfo("下雨了,天好冷");17 Log.i("兔子",message.getMsg());18 Log.i("兔子",message1.getMsg());19 Log.i("兔子",message2.getMsg());20 Log.i("兔子",message3.getMsg());21 22 }23 24 }在JAVA WEB里編寫測(cè)試單元用到的是Junit,需要導(dǎo)入jar包,在安卓開發(fā)里也有類似這樣的步驟
首先我們要在AndroidManifest.xml里的application標(biāo)簽里添加
<uses-library android:name="android.test.runner" />
然后在application外添加
<instrumentation android:name="android.test.InstrumentationTestRunner" android:label="ceshi" android:targetPackage="com.example.androidchat" ></instrumentation>
由于需要聯(lián)網(wǎng)別忘了給應(yīng)用賦予網(wǎng)絡(luò)權(quán)限
<uses-permission android:name="android.permission.INTERNET" />
這里是完整文件代碼:
1 <?xml version="1.0" encoding="utf-8"?> 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android" 3 package="com.example.androidchat" 4 android:versionCode="1" 5 android:versionName="1.0" > 6 7 <uses-sdk 8 android:minSdkVersion="8" 9 android:targetSdkVersion="21" />10 11 <uses-permission android:name="android.permission.INTERNET" />12 13 <application14 android:allowBackup="true"15 android:icon="@drawable/ic_launcher"16 android:label="@string/app_name"17 android:theme="@style/A看下我們的測(cè)試代碼效果圖:
好了,此時(shí)我們已經(jīng)可以獲取到服務(wù)端的數(shù)據(jù),并且接收到客戶端并做處理,下篇文章《安卓智能聊天機(jī)器人開發(fā)(二)》寫下關(guān)于如何嵌入到安卓應(yīng)用里。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注