1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java实现与图灵机器人聊天_调用图灵机器人API实现简单聊天

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

时间:2021-07-27 01:08:47

相关推荐

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

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

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

/openapi/api?key=1702c05fc1b94e2bb4de7fb2e61b21a3&info=hello

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

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

下面开始写代码。

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

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

1

2 xmlns:tools="/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

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

19 android:layout_width="match_parent"

20 android:layout_height="wrap_content"

21 android:layout_alignParentBottom="true"

22 android:orientation="horizontal" >

23

24

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

34 android:layout_height="wrap_content"

35 android:layout_weight="1"

36 android:background="@drawable/button1"

37 android:onClick="click" />

38

39

40

activity_main.xml

关键是点击事件的实现:

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

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

需要在onCreate里加上:

StrictMode.setThreadPolicy(newStrictMode.ThreadPolicy.Builder()

.detectDiskReads().detectDiskWrites().detectNetwork()

.penaltyLog().build());

StrictMode.setVmPolicy(newStrictMode.VmPolicy.Builder()

.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()

.penaltyLog().penaltyDeath().build());

1 packagecn.starry.gangchat.utils;2

3 importjava.io.InputStream;4 .HttpURLConnection;5 .URL;6 .URLEncoder;7

8 importorg.json.JSONObject;9

10 public classInputUtils {11 private static String APIKEY = "1702c05fc1b94e2bb4de7fb2e61b21a3";12

13 public staticString 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("/openapi/api?key="

19 + APIKEY + "&info=" +info);20 System.out.println(url);21 HttpURLConnection connection =(HttpURLConnection) url22 .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 = newJSONObject(resutl);30 out = object.getString("text");31 }32 } catch(Exception e) {33 e.printStackTrace();34 }35 returnout;36

37 }38 }

InputUtils.java

在InputUtils.java里用到了:

StreamUtils.streamToString(inputStream)

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

1 packagecn.starry.gangchat.utils;2

3 importjava.io.ByteArrayOutputStream;4 importjava.io.IOException;5 importjava.io.InputStream;6

7 public classStreamUtils {8 public staticString streamToString(InputStream in) {9 String result = "";10 try{11 //创建一个字节数组写入流

12 ByteArrayOutputStream out = newByteArrayOutputStream();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 returnresult;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 packagecn.starry.gangchat;2

3 importjava.util.Random;4

5 importcn.starry.gangchat.utils.InputUtils;6

7 importandroid.os.Bundle;8 importandroid.os.StrictMode;9 importandroid.view.View;10 importandroid.view.inputmethod.InputMethodManager;11 importandroid.widget.EditText;12 importandroid.widget.LinearLayout;13 importandroid.widget.RelativeLayout;14 importandroid.widget.TextView;15 importandroid.widget.Toast;16 importandroid.annotation.SuppressLint;17 importandroid.app.Activity;18 importandroid.content.Context;19

20 public class MainActivity extendsActivity {21

22 privateEditText et_input;23 privateTextView tv_out;24 privateRelativeLayout rl;25

26 @SuppressLint("NewApi")27 @Override28 protected voidonCreate(Bundle savedInstanceState) {29 super.onCreate(savedInstanceState);30 setContentView(R.layout.activity_main);31 int[] arr = { 0x7f020001, 0x7f020002, 0x7f020003, 0x7f020004,32 0x7f020005};33 StrictMode.setThreadPolicy(newStrictMode.ThreadPolicy.Builder()34 .detectDiskReads().detectDiskWrites().detectNetwork()35 .penaltyLog().build());36 StrictMode.setVmPolicy(newStrictMode.VmPolicy.Builder()37 .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()38 .penaltyLog().penaltyDeath().build());39 Random random = newRandom();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 voidclick(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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。