调用图灵机器人API实现简单聊天

  昨天突然想在Android下调用图灵机器人API实现聊天的功能。说干就干,虽然过程中遇见一些问题,但最后解决了的心情真好。

API接口是(key值可以在图灵机器人网站里注册得到)

www.tuling123.com/openapi/api?key=1702c05fc1b94e2bb4de7fb2e61b21a3&info=hello

最后hello是讲的话,访问这个网站会访问一个JSON格式的内容。

  text关键字就是访问的内容,只要把这个关键字的内容截取下列就行了。

下面开始写代码。

首先布个局,丑丑的别介意。

  一个TextView在上面,用来显示内容,一个EditView在下面用来输入内容,然后一个按钮实现点击事件。

 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:id="@+id/rl"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent"
 6     android:background="@drawable/background1"
 7     tools:context=".MainActivity" >
 8 
 9     <TextView
10         android:id="@+id/tv_out"
11         android:layout_width="match_parent"
12         android:layout_height="wrap_content"
13         android:textColor="#ff0000"
14         android:textIsSelectable="true"
15         android:textSize="25sp" />
16 
17     <LinearLayout
18         android:id="@+id/ll"
19         android:layout_width="match_parent"
20         android:layout_height="wrap_content"
21         android:layout_alignParentBottom="true"
22         android:orientation="horizontal" >
23 
24         <EditText
25             android:id="@+id/et_input"
26             android:layout_width="0dp"
27             android:layout_height="wrap_content"
28             android:layout_weight="4"
29             android:hint="@string/et_input"
30             android:textSize="20sp" />
31 
32         <Button
33             android:layout_width="0dp"
34             android:layout_height="wrap_content"
35             android:layout_weight="1"
36             android:background="@drawable/button1"
37             android:onClick="click" />
38     </LinearLayout>
39 
40 </RelativeLayout>
activity_main.xml

关键是点击事件的实现:

  当按钮被点击时,就获取EditView上的内容。然后用InputUtils.getString(question)封装一个方法,传一个输入的内容用来返回网页关键字"text"里的内容。

这个地方需要注意下,在调试的时候,到int code = connection.getResponseCode();这一步就不运行了,获取不了状态码,百度了下。

  需要在onCreate里加上:

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads().detectDiskWrites().detectNetwork()
                .penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
                .penaltyLog().penaltyDeath().build());
 1 package cn.starry.gangchat.utils;
 2 
 3 import java.io.InputStream;
 4 import java.net.HttpURLConnection;
 5 import java.net.URL;
 6 import java.net.URLEncoder;
 7 
 8 import org.json.JSONObject;
 9 
10 public class InputUtils {
11     private static String APIKEY = "1702c05fc1b94e2bb4de7fb2e61b21a3";
12 
13     public static String getString(String question) {
14         String out = null;
15         try {
16             String info = URLEncoder.encode(question, "utf-8");
17             System.out.println(info);
18             URL url = new URL("http://www.tuling123.com/openapi/api?key="
19                     + APIKEY + "&info=" + info);
20             System.out.println(url);
21             HttpURLConnection connection = (HttpURLConnection) url
22                     .openConnection();
23             connection.setConnectTimeout(10 * 1000);
24             connection.setRequestMethod("GET");
25             int code = connection.getResponseCode();
26             if (code == 200) {
27                 InputStream inputStream = connection.getInputStream();
28                 String resutl = StreamUtils.streamToString(inputStream);
29                 JSONObject object = new JSONObject(resutl);
30                 out = object.getString("text");
31             }
32         } catch (Exception e) {
33             e.printStackTrace();
34         }
35         return out;
36 
37     }
38 }
InputUtils.java

在InputUtils.java里用到了:

StreamUtils.streamToString(inputStream)

这个是我定义。是在一个输入流里获取内容,用utf-8编码返回。

 1 package cn.starry.gangchat.utils;
 2 
 3 import java.io.ByteArrayOutputStream;
 4 import java.io.IOException;
 5 import java.io.InputStream;
 6 
 7 public class StreamUtils {
 8     public static String streamToString(InputStream in) {
 9         String result = "";
10         try {
11             // 创建一个字节数组写入流
12             ByteArrayOutputStream out = new ByteArrayOutputStream();
13             byte[] buffer = new byte[1024];
14             int length = 0;
15             while ((length = in.read(buffer)) != -1) {
16                 out.write(buffer, 0, length);
17                 out.flush();
18             }
19             result = new String(out.toByteArray(), "utf-8");
20             out.close();
21         } catch (IOException e) {
22             e.printStackTrace();
23         }
24         return result;
25     }
26 }
StreamUtils.java

最后还实现了一个点击按钮就让软键盘隐藏的功能。

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);            
         if(imm.isActive()&&getCurrentFocus()!=null){
            if (getCurrentFocus().getWindowToken()!=null) {
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }             
         }
 1 package cn.starry.gangchat;
 2 
 3 import java.util.Random;
 4 
 5 import cn.starry.gangchat.utils.InputUtils;
 6 
 7 import android.os.Bundle;
 8 import android.os.StrictMode;
 9 import android.view.View;
10 import android.view.inputmethod.InputMethodManager;
11 import android.widget.EditText;
12 import android.widget.LinearLayout;
13 import android.widget.RelativeLayout;
14 import android.widget.TextView;
15 import android.widget.Toast;
16 import android.annotation.SuppressLint;
17 import android.app.Activity;
18 import android.content.Context;
19 
20 public class MainActivity extends Activity {
21 
22     private EditText et_input;
23     private TextView tv_out;
24     private RelativeLayout rl;
25 
26     @SuppressLint("NewApi")
27     @Override
28     protected void onCreate(Bundle savedInstanceState) {
29         super.onCreate(savedInstanceState);
30         setContentView(R.layout.activity_main);
31         int[] arr = { 0x7f020001, 0x7f020002, 0x7f020003, 0x7f020004,
32                 0x7f020005 };
33         StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
34                 .detectDiskReads().detectDiskWrites().detectNetwork()
35                 .penaltyLog().build());
36         StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
37                 .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
38                 .penaltyLog().penaltyDeath().build());
39         Random random = new Random();
40         int ran = random.nextInt(5);
41         et_input = (EditText) findViewById(R.id.et_input);
42         tv_out = (TextView) findViewById(R.id.tv_out);
43         rl = (RelativeLayout) findViewById(R.id.rl);
44          rl.setBackgroundResource(arr[ran]);
45     }
46 
47     public void click(View v) {
48         String question = et_input.getText().toString().trim();
49         if (question == null || "".equals(question)) {
50             Toast.makeText(getApplicationContext(), "请输入内容哦!",
51                     Toast.LENGTH_SHORT).show();
52             return;
53         }
54         InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);            
55          if(imm.isActive()&&getCurrentFocus()!=null){
56             if (getCurrentFocus().getWindowToken()!=null) {
57             imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
58             }             
59          }
60         String result = InputUtils.getString(question);
61         tv_out.setText(result);
62         et_input.setText("");
63     }
64 
65 }
MainActicity.java

安装包下载地址:http://123.207.118.162/downloads/Starry.apk

GitHub上有完整项目,可以直接导入在Eclipse里:https://github.com/Starry0/chat

原文地址:https://www.cnblogs.com/xingkongyihao/p/7447228.html