Android使用有道翻譯API實如今線翻譯功能

來源:互聯網
上載者:User

標籤:sonar   tracking   bsp   manager   system   stat   base   handler   android   

在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;@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.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;}@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, "要翻譯的文本過長", 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);

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

Android使用有道翻譯API實如今線翻譯功能

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.