Android app record one: Youdao Translator API call

Source: Internet
Author: User

For some reason, I need to remember the words and hate the ads, so I want to write a can check the words I do not know and can be viewed at any time the app.

first I need to call a translation API, Chinese translation more useful API has Youdao translation API, Baidu translation API, etc., because the early use of Baidu Map API, feel very useful, so I first consulted Baidu translation API

Feel good, because I wrote the app is for their own use, so it certainly enough, and then I applied for an API interface, when I read the document, Baidu for security reasons, in the current version of the interface to add a signature, through a certain input sequence to form MD5 sequence, and this feeling a little trouble, Although I tried it later, I could use it, but I didn't feel much time, and turned to the Youdao translation API.

The first thing to do is definitely to apply for key, and then read the next API Access document, found Youdao API is very simple and rude, its data interface is:

Http://fanyi.youdao.com/openapi.do?keyfrom=&key=&type=data&doctype=&version=1.1&q= the text to be translated

Official notes

Version: 1.1, request mode: Get, Encoding: Utf-8
Main functions: Chinese and English translation, while obtaining Youdao translation results and Youdao dictionary results (may not)
Parameter description:
Type-Returns the types of results, fixed to data
DOCTYPE-Returns the data format of the result, either XML or JSON or JSONP
Version-versions, currently the latest version is 1.1
Q-The text to be translated must be UTF-8 encoded, the character length cannot exceed 200 characters, need to be urlencode encoded
Only-optional parameter, dict means that only the dictionary data is obtained, translate means that only the translation data is obtained, the default is to get
Note: The dictionary results only support translation between English and Japanese, Russian and Chinese, and Chinese to English translation.
ErrorCode:
0-Normal
20-The text to be translated is too long
30-Unable to translate effectively
40-Unsupported language type
50-Invalid Key
60-No dictionary results, only in Get dictionary results effective

http//Fanyi.youdao.com/openapi.do?keyfrom=<keyfrom>&key=<key>&type=data&doctype=json &version=1.1&q=good{    "ErrorCode": 0 "Query": "Good",    "Translation": ["good"],//Youdao Translation"Basic": {//Youdao Dictionary-Basic Dictionary"Phonetic": "G?d" "uk-phonetic": "G?d"//English pronunciation"Us-phonetic": "ɡ?d"//American Pronunciation"explains":[            Benefits,            "Good" "good"        ]    },    "Web": [//Youdao Dictionary-Network interpretation        {            "Key": "Good",            "Value": ["good", "good", "good"]        },        {...} ]}

 

where I need to change Q is the object that needs to be queried, and the other can be written to the string in Java
My idea is to return the required translation data by sending an HTTP request, then parse the returned JSON, and here's the code I'm using

Private voidSentinquire (String q) {HttpClient HttpClient=Newdefaulthttpclient (); String ServerURL= URLString +Q; String data_backstring= ""; HttpPost Httprequst=NewHttpPost (ServerURL); Try{HttpResponse response=Httpclient.execute (Httprequst); if(Response.getstatusline (). Getstatuscode () = =HTTPSTATUS.SC_OK) {data_backstring= Entityutils.tostring (Response.getentity ());//receive the returned dataSystem.out.println (data_backstring); LOG.I (TAG,"Result =" +data_backstring); //The following is JSON data parsing                Try {                    //Jsonarray Jsonarray = new Jsonarray (data_backstring);Jsonobject JsonObject2 =NewJsonobject (data_backstring); //String string=jsonobject2.getstring ("translation"); //receivestring=string; //Jsonobject jsonobject3=new//Jsonobject (jsonobject2.getstring ("basic"));Jsonobject jsonObject3 =(Jsonobject) jsonObject2. Get ("Basic"); Receivestring= Jsonobject3.getstring ("explains"); Jsonarray JsonArray1=NewJsonarray (receivestring); Receivestring= "";  for(inti = 0; I < jsonarray1.length (); i++) {receivestring+ = jsonarray1.getstring (i) + "\ n"; }                    //string[] Strarray=receivestring.split (",");                     /** for (int i = 0; i < strarray.length; i++) {//string * mytemp * =strarray[i].substring ("Strarray[i].indexof"), Strarray * [I].indexof ("'")]; Receivestring+=mytemp+ "\ n"; }                     */Jsonarray Jsonarray= Jsonobject2.getjsonarray ("Web");  for(inti = 0; I < jsonarray.length (); i++) {Jsonobject Jsonobjectson=(Jsonobject) jsonarray. opt (i); Receivestring+ = jsonobjectson.getstring ("Key"); Receivestring+= ":"; //String valuetemp=jsonobjectson.getstring ("value");Jsonarray ValueArray =NewJsonarray (jsonobjectson.getstring ("Value"));  for(intj = 0; J < Valuearray.length (); J + +) {receivestring+=valuearray.getstring (j); } receivestring+ = "\ n"; } mhandler.sendemptymessage (0); } Catch(Exception e) {//Todo:handle ExceptionE.printstacktrace (); System.out.println ("-----An exception occurred------"); }            }        } Catch(Exception e) {//Todo:handle Exception        }     }

 

JSON data returned in the test program

{"Translation": ["help"], "basic": {"us-phonetic": "H?LP", "phonetic": "helper", "uk-phonetic": "Assist", "explains": ["N. A helping hand or a good thing "," Vt. Help, promote, cure, remedy, "VI." N. (help) a person's name; (Finn) Haier "]}," Query ":" Help "," ErrorCode ": 0," web ": [{" Value ": [" assist "," assist "," help Document "]," key ":" Helper "}, {"Value": ["self-needs", "personal use", "do-it-yourself"], "key": "Help Oneself"},{"value": ["Do a Favor", "do a big favor", "help solve the problem"], "key": "Helper Out"}]}
Parsing the JSON data section I learned from the csdn great God.

Special note that the sending network request can not be carried out in the main thread, which is not explained by many blogs, we just need to open up a new thread to be able to modify the view directly in the thread, you need to send a modified view via handler, for example, in the TextView display

so the core part of my application is done.
Full code

Android app record one: Youdao Translator API call

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.