之前安装了各种翻译软件后,因其频繁的广告,不得已而删除。而自己只是想要一个简易的翻译功能,帮助自己完成阅读。
今天做一个属于自己的翻译工具,只有简单的翻译功能 (包含百度翻译和谷歌翻译两种翻译方式),界面比较简单,没有优化。
下面先来看一下词典效果:
一. 百度在线翻译
百度翻译可以通过HTTP访问
GET请求方式:
http://openapi.baidu.com/public/2.0/bmt/translate?client_id=YourApiKey&q=today&from=auto&to=auto
得到Json格式的翻译结果:
"from":"en","to":"zh","trans_result":[{"src":"hello world","dst":"你好世界"}]}
Utils.java 工具类package com.why.demo.transla;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Utils {
private static final String PATH = "http://openapi.baidu.com/public/2.0/bmt/translate";
private static String API_KEY = "<span style="font-family: Verdana, Arial, Helvetica, sans-serif;">YourApiKey</span><span style="font-family: Verdana, Arial, Helvetica, sans-serif;">"; // 自己的app_id</span>
public static String upLoad(String requestText,String from, String to){
String result = "";
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("client_id", API_KEY));
params.add(new BasicNameValuePair("q",requestText));
params.add(new BasicNameValuePair("from", from));
params.add(new BasicNameValuePair("to", to));
HttpPost request = new HttpPost(PATH);
requ