Android intelligent chatbot development (1): Android chatbot

Source: Internet
Author: User

Android intelligent chatbot development (1): Android chatbot

This chatbot is a bit like an Android app that was very popular some time ago-Tom


The implementation of applications is actually very simple. There are many intelligent robot chat interfaces on the Internet. We only need to call the corresponding interfaces and comply with its API development specifications to obtain the information we want.

Here the interface I am using is -- Turing robot (http://www.tuling123.com/openapi)

This interface returns a Json string. You only need to parse the Json string to implement this application.

 

Development steps:

First, we need to register an account on the official website of the Turing robot. He will give us a unique Key. Through this Key and the corresponding API development specifications, we can develop it.


 

Then in this (http://www.tuling123.com/openapi/cloud/access_api.jsp) web site can find the relevant development Introduction

For example, the request method, parameter, and response parameter, Including the Development example, and some returned encoding information.


This is a small call case (JAVA) officially provided, and I will also post it here

1/*** call the Turing robot platform interface 2 * package to be imported: 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 ("weather in Beijing today", "UTF-8"); 7 String requesturl = "http://www.tuling123.com/openapi/api? Key = register the returned Apikey & info = "+ INFO; 8 HttpGet request = new HttpGet (requesturl); 9 HttpResponse response = httpclients.createdefadefa(cmd.exe cute (request ); 10 11 // 200 is the correct return code 12 if (response. getStatusLine (). getStatusCode () = 200) {13 String result = EntityUtils. toString (response. getEntity (); 14 System. out. println ("returned result:" + result); 15} 16}

 

Now, let's get started. I plan to write two articles on this application.

The second part will embed the obtained data into the Android app

 

First, write a tool class, which is used to obtain user input information and return the data provided by the server.

Here we use a third-party JAR package, which is provided by Google for Json data serialization and deserialization.

About Gson use I have written a note before, unfamiliar friends can look at: Gson brief use notes (http://www.cnblogs.com/lichenwei/p/3987429.html)

The Code is as follows:

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. examp Le. pojo. message. type; 16 import com. example. pojo. result; 17 import com. google. gson. gson; 18 19/** 20*21 * Help class for getting information to pass in user input characters, provide the corresponding information 22*23 */24 public class GetDataUtils {25 26 private static final String API_KEY = "enter the official KEY here "; // applied API_KEY value 27 private static final String URL = "http://www.tuling123.com/openapi/api"; // Interface request address 28 29 public String getChat (String msg) {// This method is used to obtain the Json returned by the server. Data, msg is the user's input information 30 String result = ""; // the variable that stores the server's returned information 31 InputStream inputStream = null; 32 ByteArrayOutputStream outputStream = null; 33 try {34 // request resources 35 java.net. URL url = new java.net. URL (getMsgUrl (msg); 36 HttpURLConnection httpURLConnection = (HttpURLConnection) url 37. openConnection (); // open the resource connection 38 39 // The HttpURLConnection parameter is set to 40 httpURLConnection. setReadTimeout (5*1000); 41 httpURLConn Ection. setConnectTimeout (5*1000); 42 httpURLConnection. setRequestMethod ("GET"); 43 44 inputStream = httpURLConnection. getInputStream (); // obtain the information returned by the server for receiving an input stream 45 int len =-1; 46 byte [] bs = new byte [124]; // The byte array used to receive the input stream 47 outputStream = new ByteArrayOutputStream (); // use an output stream to output the information obtained from the obtained input stream 48 49 while (len = inputStream. read (bs ))! =-1) {// read a certain number of bytes from the input stream and store them in the buffer array 50 // bs 51 outputStream. write (bs, 0, len); // write 52} 53 outputStream to the input stream. flush (); // clear the buffer 54 result = new String (outputStream. toByteArray (); // convert to string 55} catch (MalformedURLException e) {56 e. printStackTrace (); 57} catch (IOException e) {58 e. printStackTrace (); 59} finally {60 // close related resource 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); // print the test log 77 return result; 78} 79 80 private String getMsgUrl (String msg) throws UnsupportedEncodingException {81 String path = ""; 82 String info = URLEncoder. encode (msg, "UTF-8"); // convert url encoding 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 = gson. fromJson (getChat (msg), Result. class); // get the json returned by the server and convert it to the Result object. The Result object may not exist, and an exception 92 message may occur. setMsg (result. getText (); // the message may be empty. Capture Exception 93} catch (Exception e) {94 // the server may not return normal data, so there will be blank content, an exception 95 message needs to be captured. setMsg ("the server is busy, please try again later"); 96} 97 message. setTime (new Date (); 98 message. setType (Type. INCOME); 99 return message; 100} 101 102}

 

The following two are Entity classes. According to the examples provided on the official website, the returned Json string contains the code status code and text content.

1 package com. example. pojo; 2/** 3*4 * is used to map the returned Json String 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 {// Type enumeration, send, receive 14 INCOME, OUTCOME15} 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}

 

Compile a test class

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 ("hello"); 14 Message message1 = dataUtils. getInfo ("who are you"); 15 Message message2 = dataUtils. getInfo ("Do you know what JAVA is"); 16 Message message3 = dataUtils. getInfo ("It's raining, it's cool"); 17 Log. I ("rabbit", message. getMsg (); 18 Log. I ("rabbit", message1.getMsg (); 19 Log. I ("rabbit", message2.getMsg (); 20 Log. I ("rabbit", message3.getMsg (); 21 22} 23 24}

Compiling test units in java web uses Junit. jar packages need to be imported. Similar steps are also available in Android development.

First, add the application tag in AndroidManifest. xml.

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

Then add

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

Because you need to connect to the Internet, don't forget to give the application network permissions.

   <uses-permission android:name="android.permission.INTERNET" />

Here is the complete file code:

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 <application14 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 <activity21 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 <instrumentation32 android: name =" android. test. instrumentationTestRunner "33 android: label =" ceshi "34 android: targetPackage =" com. example. androidchat "> 35 </instrumentation> 36 37 </manifest>View Code

 

Let's take a look at our test code:


 

Now we can get the data from the server, receive the data from the client, and process it. In the next article, we will write down how to embed the data into the Android Application.

 


Software recommended by Android chatbots

Happy New Year with QQ and msn

Android chatbot

I chatbot and Tom

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.