基于Android的智能聊天机器人的设计与实现.docx
- 文档编号:27364059
- 上传时间:2023-06-29
- 格式:DOCX
- 页数:30
- 大小:172.62KB
基于Android的智能聊天机器人的设计与实现.docx
《基于Android的智能聊天机器人的设计与实现.docx》由会员分享,可在线阅读,更多相关《基于Android的智能聊天机器人的设计与实现.docx(30页珍藏版)》请在冰豆网上搜索。
基于Android的智能聊天机器人的设计与实现
基于Android的智能聊天机器人的设计与实现
学院名称:
专业:
班级:
学号:
姓名:
任课教师:
安卓智能聊天机器人开发
(一)
小黄鸡
这个聊天机器人有点像前段时间很火的一个安卓应用
应用的实现其实很简单,网上有许多关于智能机器人聊天的接口,我们只需要去
调用对应的接口,遵守它的API开发规,就可以获取到我们想要的信息
这里我使用的接口是图灵机器人(.tuling123./openapi/)
这个接口给我们返回的是Json字符串,我们只需要对它进行Json字符串解析,就可以实现这个应用。
开发步骤:
首先我们需要到这个图灵机器人的官网去注册一个账号,他会给我们一个唯
Key,通过这个Key和对应的API开发规,我们就可以进行开发了
TLRING-RODOi
个人中心
Xtv宵科
■.功餐辭曾卸取■
&机世军
h-
曲建■:
吠
然后在这个(.tuling123./openapi/cloud/accessapi.jsp)网址里可以找至卩相关的
开发介绍
比如:
请求方式,参数,返回参数,包括开发例,一些返回的编码等信息
營求方武
卢扯芯二:
tltt「mtUHi;_2.
时访壬:
:
get
=71^;—;仪M
忙41£
UKE-'hd
LMBrSa,
忙暂.ans現soJJPJ
用“序醫天无%孙屈事际S应用LJTF蜩曰
kc會Et非锐Hi空m1■咚诃如彳尿幸节.
WllA2±4fi311:
・典5&佰辱Bk垃毎■耳料口也
hi
:
.34^JI1:
I4T-fahIflL-taZiJO234fa]2
返回参教(JSON格式)
57?
^:
code
tent
首先,先写一个工具类,这个工具类是用来获取用户输入的信息并返回服务器提供的数据的
这里面用到了一个第三方提供的JAR包,Gson它是谷歌提供给我们用来使Json数据序列化和反序列化的
关于Gson的使用我之前写过一篇笔记,不熟悉的朋友可以看看:
Gson简要使
用笔记(.cnblogs./lichenwei/p/3987429.html)
代码如下:
具体看注释
package.example.utils;
importjava.io.ByteArrayOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.UnsupportedEncodingException;
importjava.net.HttpURLConnection;
importjava.net.MalformedURLException;
importjava.net.URLEncoder;
importjava.util.Date;
importandroid.util.Log;
import.example.pojo.Message;
import.example.pojo.Message.Type;
import.example.pojo.Result;
import.google.gson.Gson;
获取信息帮助类传入用户输入的字符,给出相对应的信息
*/
publicclassGetDataUtils{
privatestaticfinalStringAPI_KEY="这里填写官方提供的KEY";//申请的api_keyB
privatestaticfinalStringURL=".tuling123./openapi/api";〃接口请求地址
publicStringgetChat(Stringmsg){//这个方法是获取服务端返回回来的Json数据,msg为用户输入的信息
Stringresult="";//存放服务器返回信息的变量
InputStreaminputStream=null;
ByteArrayOutputStreamoutputStream=null;
try{
//进行资源请求
.URLurl=new.URL(getMsgUrl(msg));
HttpURLConnectionhttpURLConnection=(HttpURLConnection)
url
.openConnection();〃打开资源连接
//HttpURLConnection参数设定
httpURLConnection.setReadTimeout(5*1000);
httpURLConnection.setConnectTimeout(5*1000);
httpURLConnection.setRequestMethod("GET");
inputStream=httpURLConnection.getlnputStream();〃获取一个
输入流接收服务端返回的信息
intlen=-1;
byte[]bs=newbyte[124];〃用来接收输入流的字节数组outputStream=newByteArrayOutputStream();//用一个输出流来
输出刚获取的输入流所得到的信息
while((len=inputStream.read(bs))!
=-1){//从输入流中读取一定
数量的字节,并将其存储在缓冲区数组
//bs中
outputStream.write(bs,0,len);〃往输入流写入
}
outputStream.flush();〃清除缓冲区
result=newString(outputStream.toByteArray());〃转换成字符串
}catch(MalformedURLExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
//关闭相关资源
if(inputStream!
=null){
try{
inputStream.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(outputStream!
=null){
try{
outputStream.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
Log.i("tuzi","result:
"+result);//打印测试日志
returnresult;
}
privateStringgetMsgUrl(Stringmsg)throws
UnsupportedEncodingException{
Stringpath="";
Stringinfo=URLEncoder.encode(msg,"UTF-8");//转换url编码path=URL+"?
key="+API_KEY+"&info="+msg;
returnpath;
}
publicMessagegetInfo(Stringmsg){
Messagemessage=newMessage。
;
Gsongson=newGson();
try{
Resultresult=gson.fromJson(getChat(msg),Result.class);//获取至U服务器返回的json并转换为Result对象,Result对象可能不存在,会出现异常
message.setMsg(result.getText());//message可能为空,需要捕获异常
}catch(Exceptione){
//可能服务器没有返回正常数据,也就存在着空白容,需要捕获异常
message.setMsg("服务器繁忙,请稍后再试");
}
message.setTime(newDate());
message.setType(Type.lNCOME);
returnmessage;
}
}
下面这2个是实体类,根据官网提供的示例,返回的Json字符串里包含:
code
状态码,text文本容
package.example.pojo;
/**
用来映射返回Json字符串
*/
publicclassResult{
privateStringcode;
privateStringtext;
publicStringgetCode(){
returncode;
}
publicvoidsetCode(Stringcode){this.code=code;
}
publicStringgetText(){
returntext;
}
publicvoidsetText(Stringtext){this.text=text;
}
}
package.example.pojo;
importjava.util.Date;
publicclassMessage{
privateStringname;
privateStringmsg;
privateDatetime;
privateTypetype;
publicenumType{〃类型枚举,发送,接收
INCOME,OUTCOME
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicStringgetMsg(){returnmsg;
}
publicvoidsetMsg(Stringmsg){this.msg=msg;
}
publicDategetTime(){returntime;
}
publicvoidsetTime(Datetime){this.time=time;
}
publicTypegetType(){returntype;
}
publicvoidsetType(Typetype){this.type=type;
}
编写个测试类
package.example.test;
importandroid.test.AndroidTestCase;
importandroid.util.Log;
import.example.pojo.Message;
import.example.utils.GetDataUtils;
publicclassGetDataUtilsTestextendsAndroidTestCase{
publicvoidtest(){
GetDataUtilsdataUtils=newGetDataUtils();
Messagemessage=dataUtils.getInfo("你好");
Messagemessage仁dataUtils.getlnfo("你是谁");
Messagemessage2=dataUtils.getlnfo("你知道JAVA是什么吗");
Messagemessage3=dataUtils.getlnfo("下雨了,天好冷");
Log.i("兔子",message.getMsg());
Log.i("兔子",message1.getMsg());
Log.i("兔子",message2.getMsg());
Log.i("兔子",message3.getMsg());
}
}
在JAVAWEB里编写测试单元用到的是Junit,需要导入jar包,在安卓开发里也有类似这样的步骤
首先我们要在AndroidManifest.xml里的application标签里添加
name="android.test.runner"/> 然后在application外添加 name="android.test.InstrumentationTestRunner" android: label="ceshi"android: targetPackage=".example.androidchat"> 由于需要联网别忘了给应用赋予网络权限 vuses-permissionandroid: name="android.permission.lNTERNET"/>这里是完整文件代码: xmlversion="1.0"encoding="utf-8"? > android="http: //schemas.android./apk/res/android" package=".example.androidchat" android: versionCode="1" android: versionName="1.0"> android: minSdkVersion="8" android: targetSdkVersion="21"/> vuses-permissionandroid: name="android.permission」NTERNET"/> android: allowBackup="true" android: icon="@drawable/ic_launcher" android: label="@string/app_name" android: theme="@style/AppTheme"> vuses-libraryandroid: name="android.test.runner"/>vactivity android: name=".MainActivity" android: label="@string/app_name"> vactionandroid: name="android.intent.action.MAIN"/>vcategory android: name="android.intent.category.LAUNCHER"/> v/intent-filter> v/activity> v/application> vinstrumentation android: name="android.test.InstrumentationTestRunner" android: label="ceshi" android: targetPackage=".example.androidchat"> 看下我们的测试代码效果图: FED TD 3L"iM Mli44.ni nU^-«.KEd£SLjEhB.X Miqh«.MMEVLlChM TiMKtaMI Ft -jUcILzxria: Wh 3L-Z-4 "•I* 3L-MT? l 3LMIhW- 11-: 1L-M"厂 NAHil|^tiW£4L4eiW ■MflkEUV"ISEjrOIDAdrlMl LL-HLkNi4fi444 L-t.-acd[Oi.di: rwr I-lltJZaUME ruu;: : |~": 13D: =1Dr「: 牛-于=规尸忙亶址龙于■併事夬」; ■MllLl1"«dialUNriDlpFWI■■昂供・■■騎畔■-・ w.T*—<^AM.1.Jten«lfr2i£^: fc*Pd! : £-KaMi±l»,.. ■于 *==F-S±E^=tty—k壬r±I 鱼子 JL于-血■蠱料 Jtf E-*>■卅■挥ft■•豪關■□二*»Xi•• ■|■•宜■匚■豆丁) i,■mMiih-1 » AE&AKiti丸眷5刊HL—14MtWE: *-HE] XT期爭.4 ■観牛丄titBE.St 11C.. mrub■平: GlEKtcc^dcha'! isuf.-EiisdrJzba: T'tCF-'.iwr IfiLritotdilei"X4fli ItjcfriUieE S«33^lDtlCtlJDffjittil訂[DtS话口寵匕予1;・ 皿和冃、|・f*奔 Tticfiiiniec 好了,此时我们已经可以获取到服务端的数据,并且接收到客户端并做处理 篇文章中,已经实现了对网络数据的获取和处理封装,这篇文章来讲下如 何嵌入到安卓应用中。 先看下效果图: 12: 10fm my ^R5IEi-.>HlFsT1 用器杂, 从上面两图我们可以发现,这个聊天布局其实就是一个ListView,只不过它和传 统的ListView有些区别,因为它使用了多Item样式布局 首先,先来分析下基础布局: 这个界面是由3个布局文件组成,分别是主布局,发送消息样式布局,接收消息样式布局 先来看下主布局: 大布局是f杞聘布局「里面嵌套着2t钱性布局分别居于顶部和底部 中同是个Li或论翩牛,它位于顶部标题栏之T.底部输人栏之上 底郃是T椎向誹列的线恃布局.宰向芹右分别楚输入*软妓钮控件 这里是对应的主布局代码: android: divider="@null"--去除ListView的Item分割线 vRelativeLayoutxmlns: android="http: //schemas.android./apk/res/android"xmlns: tools="http: //schemas.android./tools" android: layout_width="match_parent" android: layout_height="match_parent" android: background="@drawable/chat_bg_default"> android: id="@+id/title" android: layout_width="fill_parent" android: layout_height="wrap_content" android: layout_alignParentTop="true"android: background="@drawable/title_bar"android: gravity="center" android: orientation="vertical"> vTextView android: layout_width="wrap_content" android: layout_height="fill_parent" android: layout_gravity="center" android: text="机器兔" android: textColor="@android: color/white" android: textSize="20sp"/> v/LinearLayout> vRelativeLayout android: id="@+id/bottom" android: layout_width="fill_parent" android: layout_height="55dp" android: layout_alignParentBottom="true" android: background="@drawable/bottom_bar" android: padding="5dp"> vEditText android: id="@+id/send_message" android: layout_width="fill_parent" android: layout_height="wrap_content" android: layout_alignParentLeft="true" android: layout_centerVertical="true" android: layout_marginLeft="5dp" android: layout_marginRight="5dp" android: background="@drawable/login_edit_normal"/>
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 基于 Android 智能 聊天 机器人 设计 实现