首先要到有道申请一个API,将keyfrom&key替换
http://fanyi.youdao.com/openapi.do?keyfrom=yzyzyzyz&key=613475076&type=data&doctype=json&version=1.1&only=translate&q=翻译内容
异步访问
private NewTextView txt_output;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//初始化控件
txt_output=(NewTextView) this.findViewById(R.id.txt_output);
<span style="white-space:pre"> </span>//文字可复制
<span style="white-space:pre"> </span>txt_output.setTextIsSelectable(true);
<span style="white-space:pre"> </span>//通过异步请求获取翻译结果
QueryAsyncTask asyncTask = new QueryAsyncTask();
asyncTask.execute("");
}
异步方法
@SuppressWarnings("rawtypes")
private class QueryAsyncTask extends AsyncTask {
@Override
protected void onPostExecute(Object result) {
try {
if (result != null) {
String rs = (String) result;
//解析json字符串
JSONObject j=new JSONObject(rs);
t=j.getString("translation");//译文
gode=j.getInt("errorCode");//翻译处理状态
System.out.println(t+" "+gode);
//翻译结果状态
if(gode==0){
//["返回结果"] 字符串的长度-截取开始的长度=返回结果字符串
int end=t.length()-2;
String out=t.substring(2, end);
//翻译结果赋值
txt_output.setText(out);
}else if(gode==20){
Toast.makeText(getApplicationContext(), "要翻译的文本过长", 200).show();
}else if(gode==30){
Toast.makeText(getApplicationContext(), "无法进行有效的翻译", 200).show();
}else if(gode==40){
Toast.makeText(getApplicationContext(), "不支持的语言类型", 200).show();
}else if(gode==50){
Toast.makeText(getApplicationContext(), "无效的key", 200).show();
}else {
Toast.makeText(getApplicationContext(), "无词典结果,仅在获取词典结果生效", 200).show();
}
} else {
Toast.makeText(getApplicationContext(), "内容有误", 200).show();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
super.onPostExecute(result);
}
@Override
protected Object doInBackground(Object... params) {
// return HttpService.getWeather(districtName);
return gettxt(txt);//获取翻译返回的结果 json格式
}
}
/*
* 将内容进行翻译
*/
public static String gettxt(String txt) {
String result = null;
//将空格转化为HTML编码
String txt1=txt.replace(" ", "%20");
//在有道申请的API
String url="http://fanyi.youdao.com/openapi.do?keyfrom=yzyzyzyz" +
"&key=613475076&type=data&doctype=json&version=1.1" +
"&only=translate&q="+txt1;
try {
DefaultHttpClient client = getDefaultHttpClient2();
HttpGet mothod = new HttpGet(url);
//设置代理
HttpResponse httpResponse = client.execute(mothod);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
result = EntityUtils.toString(httpResponse.getEntity(),"utf-8");
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
return result;
}
}
代理方法
private static DefaultHttpClient getDefaultHttpClient2() {
DefaultHttpClient client;
HttpParams httpParams = new BasicHttpParams();
// 设置代理
String host = android.net.Proxy.getDefaultHost();
int port = android.net.Proxy.getDefaultPort();
// Log.v(TAG,"代理:"+host+",端口:"+port);
if (host != null) {
HttpHost httpHost = new HttpHost(host, port);
httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, httpHost);
}
// 设置超时
HttpConnectionParams.setConnectionTimeout(httpParams, 20000);
HttpConnectionParams.setSoTimeout(httpParams, 20000);
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
schReg.register(new Scheme("https",
SSLSocketFactory.getSocketFactory(), 443));
// 使用线程安全的连接管理来创建HttpClient
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
httpParams, schReg);
client = new DefaultHttpClient(conMgr, httpParams);
return client;
}