Android use Youdao translation API real line translation function

Source: Internet
Author: User

In Android app, add the function of online translator, here is the Youdao translation API.

Use Youdao translation API. First of all to apply for a key, the application address is: Youdao translation API application address.


After applying, you will get a Keyfrom and a key.

The data interface for obtaining the translation results is:http://fanyi.youdao.com/openapi.do?

keyfrom=<keyfrom>&key=<key>&type=data&doctype=<doctype >&version=1.1&q= the text to be translated. We just need to stitch things up like this. The way to use get. will be able to get the result of the translation.

I translated the "program Ape", the data returned by the interface is:

{"    translation": [        "the programmer"    ],    "basic": {        "phonetic": "Chéng Xùyuán",        "explains": [            "Programmer"        ]    },    "Query": "Program Ape",    "ErrorCode": 0,    "web": [        {            "value": [                " Programmer ",                " coder ",                " SCJP "            ],            " key ":" Program Ape "        },        {            " value ": [                " Systems Programmer ",                " Java Card ",                " System Programmer "            ],            " key ":" Program Ape "        },        {            " value ": [                "Programmer",                "computer programmer",                "Job-interviewcomputer programmer"            ],            "key": "Computer program Ape"        }    ]}
We just need to parse out what we need.

Detailed implementations such as the following:

public class Mainactivity extends Activity {private EditText edit = null;private TextView search = null;private TextView t ext = null;private String youdaobaseurl = "Http://fanyi.youdao.com/openapi.do";p rivate string youdaokeyfrom = " Youdaokeyfrom ";p rivate string youdaokey =" Youdaokey ";p rivate string youdaotype =" Data ";p rivate string youdaodoctype =" J Son ";p rivate String youdaoversion =" 1.1 ";p rivate translatehandler handler;private static final int succee_result = 10;pri vate static final int error_text_too_long = 20;private static final int error_cannot_translate = 30;private static final I  NT Error_unsupport_language = 40;private static final int error_wrong_key = 50;private static final int Error_wrong_result = @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); edit = (EditText) Findviewbyid (r.id.edit); search = (TextView) Findviewbyid (R.id.search); Search.setonclicklistener (New Searchlistener ()); TeXT = (TextView) Findviewbyid (r.id.text); handler = new Translatehandler (this, text);} Private class Searchlistener implements Onclicklistener {@Overridepublic void OnClick (View v) {String content = Edit.gette XT (). toString (). Trim (); if (content = = NULL | | ". Equals (content)) {Toast.maketext (Getapplicationcontext ()," Please enter the content to be translated ", Toast.length_short). Show (); return;} Final String Youdaourl = Youdaobaseurl + "? keyfrom=" + Youdaokeyfrom + "&key=" + Youdaokey + "&type=" + youdaotype + "&doctype=" + Youdaodoctype + "&type=" + Youdaotype + "&version=" + youdaoversion+ "&q=" + content;new T Hread () {public void run () {try {Analyzingofjson (youdaourl);} catch (Exception e) {e.printstacktrace ()}};}. Start ();}} private void Analyzingofjson (String url) throws Exception {//First step, create HttpGet object HttpGet httpget = new HttpGet (URL);//second step, use E The Xecute method sends an HTTP GET request. and returns the HttpResponse object HttpResponse HttpResponse = new Defaulthttpclient (). Execute (httpget); Httpresponse.getstatusline (). Getstatuscode () = = 200) {//Third step. The GetEntity method is used to return the result string results = Entityutils.tostring (httpresponse.getentity ()); SYSTEM.OUT.PRINTLN ("Result:" + result); Jsonarray Jsonarray = new Jsonarray ("[" + result + "]"); String message = null;for (int i = 0; i < jsonarray.length (); i++) {Jsonobject jsonobject = Jsonarray.getjsonobject (i); if (jsonobject! = null) {String ErrorCode = jsonobject.getstring ("ErrorCode"); if (Errorcode.equals ("20")) { Handler.sendemptymessage (Error_text_too_long);} else if (errorcode.equals (")") {handler.sendemptymessage (error_cannot_translate);} else if (errorcode.equals (")") {handler.sendemptymessage (error_unsupport_language);} else if (Errorcode.equals ("50 ")) {handler.sendemptymessage (error_wrong_key);}  else {message msg = new Message (); msg.what = succee_result;//the content to translate string query = jsonobject.getstring ("query"); "Translation result:";//translation content Gson Gson = new Gson (); Type lt = new typetoken<string[]> () {}.gettype (); String[] Translations = Gson.fromjson (Jsonobject.getstring ("trAnslation "), lt); for (String translation:translations) {message + =" \ t "+ translation;} Youdao Dictionary-Basic Dictionary if (Jsonobject.has ("basic")) {Jsonobject basic = Jsonobject.getjsonobject ("basic"); if (Basic.has (" Phonetic ")) {String phonetic = basic.getstring (" phonetic ");//Message + =" \n\t "+ phonetic;} if (Basic.has ("explains")) {String explains = Basic.getstring ("explains");//Message + = "\n\t" + explains;}} Youdao Dictionary-Network interpretation if (Jsonobject.has ("Web")) {String web = jsonobject.getstring ("web"); Jsonarray webstring = new Jsonarray ("[" + web + "]"); message + = "\ n Network interpretation:"; Jsonarray Webarray = webstring.getjsonarray (0); int count = 0;while (!webarray.isnull (count)) {if ( Webarray.getjsonobject (count). has ("key")) {String key = Webarray.getjsonobject (count). GetString ("key"); message + = "\ N ("+ (count + 1) +") "+ key +" \ n ";} if (Webarray.getjsonobject (count). has ("value")) {string[] values = Gson.fromjson (Webarray.getjsonobject (count). GetString ("value"), lt); for (int j = 0; J < Values.length; J + +) {String value = VAlues[j];message + = Value;if (J < values.length-1) {message + = ". ";}}} count++;}} Msg.obj = Message;handler.sendmessage (msg);}}} Text.settext (message);} else {handler.sendemptymessage (error_wrong_result);}} Private class Translatehandler extends Handler {private Context mcontext;private TextView mtextview;public Translatehandler (context context, TextView TextView) {this.mcontext = Context;this.mtextview = TextView;} @Overridepublic void Handlemessage (Message msg) {switch (msg.what) {case SUCCEE_RESULT:mTextView.setText (String) Msg.obj); Closeinput (); Break;case ERROR_TEXT_TOO_LONG:Toast.makeText (Mcontext, "the text to be translated is too long", toast.length_short). Show (); Break;case ERROR_CANNOT_TRANSLATE:Toast.makeText (Mcontext, "cannot be translated effectively", Toast.length_short). Show (); break; Case ERROR_UNSUPPORT_LANGUAGE:Toast.makeText (Mcontext, "Unsupported language type", Toast.length_short). Show (); Break;case error_ WRONG_KEY:Toast.makeText (Mcontext, "Invalid KEY", Toast.length_short). Show (); Break;case Error_wrong_result: Toast.maketext (Mcontext, "extracting exception", Toast.length_short). Show (); break;default:break;} Super.handlemessage (msg);}} public void Closeinput () {Inputmethodmanager Inputmethodmanager = (inputmethodmanager) getsystemservice (Context.INPUT _method_service); if ((Inputmethodmanager! = null) && (this.getcurrentfocus () = null)) { Inputmethodmanager.hidesoftinputfromwindow (This.getcurrentfocus (). Getwindowtoken (), InputMethodManager.HIDE_NOT _always);}}}
Look at the effect:



Supplement: The translated text should be coded to be competent enough to prevent special characters.

Urlencoder.encode (content);

demo:http://download.csdn.net/detail/u014375869/8844145

Android use Youdao translation API real line translation function

Related Article

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.