zoukankan      html  css  js  c++  java
  • 安卓智能聊天机器人开发(一)

    这个聊天机器人有点像前段时间很火的一个安卓应用——小黄鸡

    应用的实现其实很简单,网上有许多关于智能机器人聊天的接口,我们只需要去调用对应的接口,遵守它的API开发规范,就可以获取到我们想要的信息

    这里我使用的接口是——图灵机器人(http://www.tuling123.com/openapi/)

    这个接口给我们返回的是Json字符串,我们只需要对它进行Json字符串解析,就可以实现这个应用。

    开发步骤:

    首先我们需要到这个图灵机器人的官网去注册一个账号,他会给我们一个唯一Key,通过这个Key和对应的API开发规范,我们就可以进行开发了。

    然后在这个(http://www.tuling123.com/openapi/cloud/access_api.jsp)网址里可以找到相关的开发介绍

    比如:请求方式,参数,返回参数,包括开发范例,一些返回的编码等信息

    这里是官方提供的一个调用小案例(JAVA),这里我也顺带贴一下

     1 /** 调用图灵机器人平台接口 
     2 * 需要导入的包: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= 注册激活返回的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("返回结果:"+result); 
    15     } 
    16 }

    好了,接下来开始实战吧,这个应用我打算写成两篇文章

    第一篇讲下关于如何调用接口,从网上获取数据,包括解析Json字符串

    第二篇会把这些获取的数据嵌入到安卓应用

    首先,先写一个工具类,这个工具类是用来获取用户输入的信息并返回服务器提供的数据的

    这里面用到了一个第三方提供的JAR包,Gson它是谷歌提供给我们用来使Json数据序列化和反序列化的

    关于Gson的使用我之前写过一篇笔记,不熟悉的朋友可以看看:Gson简要使用笔记http://www.cnblogs.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  * 获取信息帮助类 传入用户输入的字符,给出相对应的信息
     22  * 
     23  */
     24 public class GetDataUtils {
     25 
     26     private static final String API_KEY = "这里填写官方提供的KEY";// 申请的API_KEY值
     27     private static final String URL = "http://www.tuling123.com/openapi/api";// 接口请求地址
     28 
     29     public String getChat(String msg) {//这个方法是获取服务端返回回来的Json数据,msg为用户输入的信息
     30         String result = "";// 存放服务器返回信息的变量
     31         InputStream inputStream = null;
     32         ByteArrayOutputStream outputStream = null;
     33         try {
     34             // 进行资源请求
     35             java.net.URL url = new java.net.URL(getMsgUrl(msg));
     36             HttpURLConnection httpURLConnection = (HttpURLConnection) url
     37                     .openConnection();// 打开资源连接
     38 
     39             // HttpURLConnection参数设定
     40             httpURLConnection.setReadTimeout(5 * 1000);
     41             httpURLConnection.setConnectTimeout(5 * 1000);
     42             httpURLConnection.setRequestMethod("GET");
     43 
     44             inputStream = httpURLConnection.getInputStream();// 获取一个输入流接收服务端返回的信息
     45             int len = -1;
     46             byte[] bs = new byte[124];// 用来接收输入流的字节数组
     47             outputStream = new ByteArrayOutputStream();// 用一个输出流来输出刚获取的输入流所得到的信息
     48 
     49             while ((len = inputStream.read(bs)) != -1) {// 从输入流中读取一定数量的字节,并将其存储在缓冲区数组
     50                                                         // bs 中
     51                 outputStream.write(bs, 0, len);// 往输入流写入
     52             }
     53             outputStream.flush();// 清除缓冲区
     54             result = new String(outputStream.toByteArray());// 转换成字符串
     55         } catch (MalformedURLException e) {
     56             e.printStackTrace();
     57         } catch (IOException e) {
     58             e.printStackTrace();
     59         } finally {
     60             // 关闭相关资源
     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);//打印测试日志
     77         return result;
     78     }
     79 
     80     private String getMsgUrl(String msg) throws UnsupportedEncodingException {
     81         String path = "";
     82         String info = URLEncoder.encode(msg, "UTF-8");// 转换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);//获取到服务器返回的json并转换为Result对象,Result对象可能不存在,会出现异常
     92             message.setMsg(result.getText());//message可能为空,需要捕获异常
     93         } catch (Exception e) {
     94             //可能服务器没有返回正常数据,也就存在着空白内容,需要捕获异常
     95             message.setMsg("服务器繁忙,请稍后再试");
     96         }
     97         message.setTime(new Date());
     98         message.setType(Type.INCOME);
     99         return message;
    100     }
    101 
    102 }

    下面这2个是实体类,根据官网提供的示例,返回的Json字符串里包含:code状态码,text文本内容

     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{//类型枚举,发送,接收
    14         INCOME,OUTCOME
    15     }
    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 }

    编写个测试类

     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("你是谁");
    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里编写测试单元用到的是Junit,需要导入jar包,在安卓开发里也有类似这样的步骤

    首先我们要在AndroidManifest.xml里的application标签里添加

     <uses-library android:name="android.test.runner" />

    然后在application外添加  

    <instrumentation android:name="android.test.InstrumentationTestRunner" android:label="ceshi" android:targetPackage="com.example.androidchat" >
    </instrumentation>

    由于需要联网别忘了给应用赋予网络权限

       <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     <application
    14         android:allowBackup="true"
    15         android:icon="@drawable/ic_launcher"
    16         android:label="@string/app_name"
    17         android:theme="@style/AppTheme" >
    18         <uses-library android:name="android.test.runner" />
    19 
    20         <activity
    21             android:name=".MainActivity"
    22             android:label="@string/app_name" >
    23             <intent-filter>
    24                 <action android:name="android.intent.action.MAIN" />
    25 
    26                 <category android:name="android.intent.category.LAUNCHER" />
    27             </intent-filter>
    28         </activity>
    29     </application>
    30 
    31     <instrumentation
    32         android:name="android.test.InstrumentationTestRunner"
    33         android:label="ceshi"
    34         android:targetPackage="com.example.androidchat" >
    35     </instrumentation>
    36 
    37 </manifest>

    看下我们的测试代码效果图:

    好了,此时我们已经可以获取到服务端的数据,并且接收到客户端并做处理,下篇文章《安卓智能聊天机器人开发(二)》写下关于如何嵌入到安卓应用里。

  • 相关阅读:
    Chrome调试工具常用功能
    把读取sql的结果写入到excel文件
    Android逆向破解:Android Killer使用
    鸭子类型和猴子补丁
    Scrapy同时启动多个爬虫
    命令注入
    理解RESTful架构
    程序员需要谨记的九大安全编码规则
    10条建议分享:帮助你成为与硅谷工程师一样优秀的程序员
    代码审计:是安全专家都应该掌握的技能
  • 原文地址:https://www.cnblogs.com/lichenwei/p/4080202.html
Copyright © 2011-2022 走看看