毕设想要实现一个在英语语境下的聊天机器人的功能,经过老师同意,决定先调用图灵机器人的API去实现功能,完了再说自己写的事情8!
开始:
- 要使用图灵机器人的API需要先注册,获取APIKEY才行,注册一个账号去吧。网址:http://www.tuling123.com/
- 一个非常简单的布局,见3.
-
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp"> <TextView android:id="@+id/out_tv" android:layout_width="match_parent" android:layout_height="wrap_content" android:textIsSelectable="true" /> <LinearLayout android:id="@+id/ll" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_alignParentBottom="true"> <EditText android:id="@+id/input_et" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="3" android:hint="在这里输入聊天内容吧"/> <Button android:id="@+id/send_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:layout_marginLeft="6dp" android:text="发 送" android:onClick="click"/> </LinearLayout> </RelativeLayout>
- 输入工具类,封装这个方法,传入一个输入的内容用来返回内容,见5.
-
public class InputUtils { private static String APIKEY = "这里写自己的APIKEY"; public static String getString(String question){ String out = null; try { String info = URLEncoder.encode(question,"utf-8"); URL url = new URL("http://www.tuling123.com/openapi/api?key=" + APIKEY + "&info=" + info); System.out.println(url); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(10 * 1000); connection.setRequestMethod("GET"); int code = connection.getResponseCode(); if (code == 200){ InputStream inputStream = connection.getInputStream(); String result = StreamUtils.steamToString(inputStream); JSONObject object = new JSONObject(result); out = object.getString("text"); } } catch (Exception e) { e.printStackTrace(); } return out; } }
- 用utf-8编码返回输入流里的内容的工具类,上面的工具类有调用到这个,见7.
-
public class StreamUtils { public static String steamToString(InputStream in) { String result = ""; try { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length = 0; while ((length = in.read(buffer)) != -1) { out.write(buffer, 0, length); out.flush(); } result = new String(out.toByteArray(), "utf-8"); out.close(); } catch (IOException e) { e.printStackTrace(); } return result; } }
- 最后在MainActivity中添加一个按钮跳转过来,这就不写啦
效果:如图。
总结:这次达到了用图灵API实现聊天机器人的目的,而具体的聊天记录和语料库还缺乏,毕竟我要的是英文对话,而它还不能说英文呀,继续学习……
感谢:这次学习,是看了一个大神的博客,他来自https://www.cnblogs.com/xingkongyihao/p/7447228.html,非常感谢。