Android uses Youdao translation API to implement online translator function
Last Update:2015-06-27
Source: Internet
Author: User
<span id="Label3"></p><p><p>In Android app, add the function of online translator, here is the Youdao translation Api.</p></p><p><p>Use Youdao translation api, the first to apply for a key, the application address is: Youdao translation API application Address.</p></p><p><p><br></p></p><p><p>After applying, you will get a <span style="font-family:arial,sans-serif; color:#666666"> <span style="font-size:14px; line-height:30px">Keyfrom and a key. </span></span></p></p><p><span style="font-family:arial,sans-serif; color:#666666"><span style="font-size:14px; line-height:30px">The data interface that gets the translation results is:<span class="host" style="margin:0px; border:0px; padding:0px; color:rgb(102,102,102); font-family:arial,sans-serif; font-size:14px; line-height:30px"><span class="host" style="margin:0px; border:0px; padding:0px; color:rgb(102,102,102); font-family:arial,sans-serif; font-size:14px; line-height:30px">http://fanyi.youdao.com/openapi.do?</span></span><span class="path" style="margin:0px; border:0px; padding:0px; color:rgb(102,102,102); font-family:arial,sans-serif; font-size:14px; line-height:30px"><span class="path" style="margin:0px; border:0px; padding:0px; color:rgb(102,102,102); font-family:arial,sans-serif; font-size:14px; line-height:30px">keyfrom=<span class="realKeyfrom" style="margin:0px; border:0px; padding:0px"><keyfrom></span>&key=<span class="realKey" style="margin:0px; border:0px; padding:0px"><key></span> </span></span><span class="para" style="margin:0px; border:0px; padding:0px; color:rgb(102,102,102); font-family:arial,sans-serif; font-size:14px; line-height:30px"><span class="para" style="margin:0px; border:0px; padding:0px; color:rgb(102,102,102); font-family:arial,sans-serif; font-size:14px; line-height:30px">&type=data&doctype=<doctype>&version=1.1</span></span><span class="query" style="margin:0px; border:0px; padding:0px; color:rgb(102,102,102); font-family:arial,sans-serif; font-size:14px; line-height:30px"><span class="query" style="margin:0px; border:0px; padding:0px; color:rgb(102,102,102); font-family:arial,sans-serif; font-size:14px; line-height:30px">&q= the text to be Translated. We just need to stitch the content up so that we can get the result of the translation using Get. </span></span></span></span></p><p><p><span style="font-family:arial,sans-serif; color:#666666"><span style="font-size:14px; line-height:30px"><span class="query" style="margin:0px; border:0px; padding:0px; color:rgb(102,102,102); font-family:arial,sans-serif; font-size:14px; line-height:30px">I translated the "programmer", the data returned by the interface is:</span></span></span></p></p><p><p> <span style="font-family:arial,sans-serif; color: #666666"><span style="font-size:14px; line-height:30px"><span class="query" style="margin:0px; border:0px; padding:0px; Color:rgb (102,102,102); font-family:arial,sans-serif; font-size:14px; line-height:30px "> </span> </span> </span> </p></p><pre name="code" class="html"><pre name="code" class="html">{" translation": [ "the programmer" ], "basic": { "phonetic": "chéng xùyuán", "explains": [ "programmer" ] }, "query": "programmer", "errorCode": 0, "web": [ { "value": [ " Programmer ", " coder ", " SCJP " ], " key ":" programmer " }, { " value ": [ " Systems Programmer ", " Java Card ", " system Programmer " ], " key ":" Systems programmer " }, { " value ": [ "programmer", "computer programmer", "job-interviewcomputer programmer" ], "key": "computer programmer" } ]}</pre></pre>We just have to parse out what we need from it.<p><p></p></p><p><p><span style="font-family:arial,sans-serif; color:#666666"><span style="font-size:14px; line-height:30px"><span class="query" style="margin:0px; border:0px; padding:0px; color:rgb(102,102,102); font-family:arial,sans-serif; font-size:14px; line-height:30px">The specific implementation is as Follows:</span></span></span></p></p><p><p><span style="font-family:arial,sans-serif; color:#666666"><span style="font-size:14px; line-height:30px"><span class="query" style="margin:0px; border:0px; padding:0px; color:rgb(102,102,102); font-family:arial,sans-serif; font-size:14px; line-height:30px"></span></span></span></p></p><pre name="code" class="java">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, using the GetEntity method to return the result of 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);}}}</pre>Look at the Effect:<p><p></p></p><p><p><span style="font-family:arial,sans-serif; color:#666666"><span style="font-size:14px; line-height:30px"><span class="query" style="margin:0px; border:0px; padding:0px; color:rgb(102,102,102); font-family:arial,sans-serif; font-size:14px; line-height:30px"><br><br></span></span></span></p></p><p><p></p></p><p><p>demo:http://download.csdn.net/detail/u014375869/8844145</p></p> <p style="font-size:12px;"><p style="font-size:12px;">Copyright Notice: This article for Bo Master original article, without Bo Master permission not Reproduced.</p></p> <p><p>Android uses Youdao translation API to implement online translator function</p></p></span>