在Android應用中,加入在線翻譯的功能,這里調用的是有道翻譯的API。
使用有道翻譯API。首先要申請一個key,申請地址為:有道翻譯API申請地址。
申請之后就會得到一個keyfrom和一個key。
獲取翻譯結果的數據接口為:http://fanyi.youdao.com/openapi.do?
keyfrom=<keyfrom>&key=<key>&type=data&doctype=<doctype>&version=1.1&q=要翻譯的文本。我們僅僅須要把內容拼接成這樣。使用GET的方式。就能得到翻譯的結果。
我翻譯了“程序猿”,接口返回的數據為:
{ "translation": [ "The programmer" ], "basic": { "phonetic": "chéng xù yuán", "explains": [ "programmer" ] }, "query": "程序猿", "errorCode": 0, "web": [ { "value": [ "Programmer", "CODER", "SCJP" ], "key": "程序猿" }, { "value": [ "Systems Programmer", "Java Card", "system programmer" ], "key": "系統程序猿" }, { "value": [ "programmer", "computer programmer", "Job-InterviewComputer Programmer" ], "key": "電腦程序猿" } ] }我們僅僅須要從中解析出我們所須要的內容就可以。
詳細實現例如以下:
public class MainActivity extends Activity { private EditText edit = null; private TextView search = null; private TextView text = null; private String YouDaoBaseUrl = "http://fanyi.youdao.com/openapi.do"; private String YouDaoKeyFrom = "YouDaoKeyFrom"; private String YouDaoKey = "YouDaoKey"; private String YouDaoType = "data"; private String YouDaoDoctype = "json"; private String YouDaoVersion = "1.1"; private TranslateHandler handler; private static final int SUCCEE_RESULT = 10; private static final int ERROR_TEXT_TOO_LONG = 20; private static final int ERROR_CANNOT_TRANSLATE = 30; private static final int ERROR_UNSUPPORT_LANGUAGE = 40; private static final int ERROR_WRONG_KEY = 50; private static final int ERROR_WRONG_RESULT = 60; @Override protected 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 { @Override public void onClick(View v) { String content = edit.getText().toString().trim(); if (content == null || "".equals(content)) { Toast.makeText(getApplicationContext(), "請輸入要翻譯的內容", Toast.LENGTH_SHORT).show(); return; } final String YouDaoUrl = YouDaoBaseUrl + "?keyfrom=" + YouDaoKeyFrom + "&key=" + YouDaoKey + "&type=" + YouDaoType + "&doctype=" + YouDaoDoctype + "&type=" + YouDaoType + "&version=" + YouDaoVersion + "&q=" + content; new Thread() { public void run() { try { AnalyzingOfJson(YouDaoUrl); } catch (Exception e) { e.printStackTrace(); } }; }.start(); } } private void AnalyzingOfJson(String url) throws Exception { // 第一步,創建HttpGet對象 HttpGet httpGet = new HttpGet(url); // 第二步,使用execute方法發送HTTP GET請求。並返回HttpResponse對象 HttpResponse httpResponse = new DefaultHttpClient().execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == 200) { // 第三步。使用getEntity方法活得返回結果 String result = 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("30 ")) { handler.sendEmptyMessage(ERROR_CANNOT_TRANSLATE); } else if (errorCode.equals("40")) { handler.sendEmptyMessage(ERROR_UNSUPPORT_LANGUAGE); } else if (errorCode.equals("50")) { handler.sendEmptyMessage(ERROR_WRONG_KEY); } else { Message msg = new Message(); msg.what = SUCCEE_RESULT; // 要翻譯的內容 String query = jsonObject.getString("query"); message = "翻譯結果:"; // 翻譯內容 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; } // 有道詞典-基本詞典 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; } } // 有道詞典-網絡釋義 if (jsonObject.has("web")) { String web = jsonObject.getString("web"); JSONArray webString = new JSONArray("[" + web + "]"); message += "\n網絡釋義:"; 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; } @Override public 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, "要翻譯的文本過長", Toast.LENGTH_SHORT).show(); break; case ERROR_CANNOT_TRANSLATE: Toast.makeText(mContext, "無法進行有效的翻譯", Toast.LENGTH_SHORT).show(); break; case ERROR_UNSUPPORT_LANGUAGE: Toast.makeText(mContext, "不支持的語言類型", Toast.LENGTH_SHORT).show(); break; case ERROR_WRONG_KEY: Toast.makeText(mContext, "無效的key", Toast.LENGTH_SHORT).show(); break; case ERROR_WRONG_RESULT: Toast.makeText(mContext, "提取異常", 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); } } }看一下效果:
補充:翻譯的文本應該要經過編碼才干夠,防止特殊字符。
URLEncoder.encode(content);