Realization of "Xiao Kun" in Intelligent Robot (II.) to get the server Data tool class writing and testing

Source: Internet
Author: User

A friend who has not been certified by a Turing device can see an article, click on the following address:

Http://www.cnblogs.com/fuly550871915/p/4852148.html

A friend who has been certified can continue to do so. Let's start with our actual code writing. In this article, we want to implement the function of retrieving the returned data by invoking the Turing-man API. and set up the appropriate test environment to see if our function is correct.

First, the implementation of the tool class to obtain the server return data

It is mainly the use of simple network programming knowledge in Android. The code is as follows:

1  PackageCom.fuly.kun.util;2 3 ImportJava.io.BufferedReader;4 ImportJava.io.ByteArrayOutputStream;5 Importjava.io.IOException;6 ImportJava.io.InputStream;7 ImportJava.io.InputStreamReader;8 Importjava.io.UnsupportedEncodingException;9 Importjava.net.HttpURLConnection;Ten Importjava.net.MalformedURLException; One Importjava.net.ProtocolException; A ImportJava.net.URL; - ImportJava.net.URLEncoder; - Importjava.util.Date; the  - ImportAndroid.util.Log; -  - ImportCOM.FULY.KUN.BEAN.CHATMSG; + ImportCom.fuly.kun.bean.ChatMsg.Type; - ImportCOM.FULY.KUN.BEAN.RESULTMSG; + ImportCom.google.gson.Gson; A Importcom.google.gson.JsonSyntaxException; at  -  - //This class is used to send messages to the server and to process the data returned from the server -  Public classHttputil { -  -      in      -      to      +     //This method is used to process the data returned from the server -      Public Staticstring Doget (String msg) { the          *         //get the appropriate URL $URL Msgurl =Setmsgparam (msg);Panax Notoginseng          -          the  +HttpURLConnection connection =NULL; A         Try { the                 //then start a connection to the server +Connection =(HttpURLConnection) msgurl.openconnection (); -                  $Connection.setrequestmethod ("GET"); $Connection.setconnecttimeout (5000); -Connection.setreadtimeout (5000); -}Catch(protocolexception e) { the          - e.printstacktrace ();Wuyi}Catch(IOException e) { the              - e.printstacktrace (); Wu             } -InputStream in =NULL; About         Try { $             //get input stream to read under face -              -in =Connection.getinputstream (); -BufferedReader reader =NewBufferedReader (NewInputStreamReader (in)); AStringBuilder response =NewStringBuilder (); + String Line; the              while(line = Reader.readline ())! =NULL){ - Response.append (line); $             } the              theString str =response.tostring (); the             //because of the discovery of JSON data returned from the server side, often with special characters <br> the             //So here we specifically replace the special character with the escape character \ n -str = str.replace ("<br>", "\ n")); in             returnstr; the              the}Catch(IOException e) { About              the e.printstacktrace (); the}finally{ the             if(Connection! =NULL){ + Connection.disconnect (); -             } the             if(In! =NULL){Bayi                 Try { the in.close (); the}Catch(IOException e) { - e.printstacktrace (); -                 } the             } the         } the          the         return NULL; -          the     } the  the     //This method is used to return the corresponding URL94     Private StaticURL Setmsgparam (String msg) { the          the         //Note that you should write your own API key here theString APIKEY = "761B4F79EBDF8B26D0BF7E0C816B32B4"; 98          About           Try { -               //set the encoding format to Utf-8, and don't forget this step101String mmsg = Urlencoder.encode (msg, "Utf-8"); 102String GetURL = "http://www.tuling123.com/openapi/api?key=" + APIKEY + "&info=" +mmsg;103URL GETURL =NewURL (GetURL);104              the             returnGetUrl;106}Catch(unsupportedencodingexception e) {107 e.printstacktrace ();108}Catch(malformedurlexception e) {109 e.printstacktrace (); the         } 111          the           return NULL;113          the     } the      the}

Note, be sure to fill in the correct API key

Second, write the class to test the Httputil.

Here, we first need to test the above tool class httputil to ensure that the tool class is correct in order to go down. Otherwise, if there is an error, you do not know whether it is because of tool class errors or other code errors, not good discriminant.

In Android, to write a test class, you first build a test environment.

Add the following code to the Androidmanifest.xml file:

1  <           2= "Android.test.InstrumentationTestRunner"3        Android : targetpackage= "Com.fuly.kun"></instrumentation>

The above code shows that the package we are going to test is com.fuly.kun (this should be changed to the reader's own set of package names).

then add the following statement in the Androidmanifest.xml:

<android:name= "Android.test.runner"/>

This sentence must be placed in the application tag .

Well, we'll set up the test environment like this.

Then create a new package com.fuly.kun.test, under which you create a new test class httputiltest, inherited from Androidtestcase. The code is as follows:

1  Packagecom.fuly.kun.test;2 3 ImportCom.fuly.kun.util.HttpUtil;4 5 Importandroid.test.AndroidTestCase;6 ImportAndroid.util.Log;7 8 //Test class Httputil9  Public classHttputiltestextendsandroidtestcase{Ten      One      A      Public voidTestsendinfo () { -          -LOG.E ("Fu Yong Kun 1--->", httputil.doget ("Hello")); theLOG.E ("Fu Yong Kun 2--->", httputil.doget ("Tell Me a Joke")); -     } -  -}

As you can see, here we send two messages to the server (that is, send a message to the robot), "Hello", "Tell me a joke". The data returned by the server is then printed out. If it prints correctly, the test is passed.

Let's right-click the project name, run as, and select Android JUnit Test (Android unit testing). The printed information is then found in the Logcat, indicating that the test passed.

Well, at this point, we can make sure that the tool class we implement is correct. You can then write the code for the next step.

Realization of "Xiao Kun" in Intelligent Robot (II.) to get the server Data tool class writing and testing

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.