package com.translate.util;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Random;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.json.JSONException;
import org.json.JSONObject;
public class YDTranslateUtil {
/**
*应用id
*/
private static final String APP_ID = "xxx";
/**
*应用密钥
*/
private static final String APP_KEY = "xxx";
/**
*翻译的接口地址
*/
private static final String BASE_URL = "http://openapi.youdao.com/api";
private static final String PARAM_Q = "?q=";
private static final String PARAM_FROM = "&from=";
private static final String PARAM_TO = "&from=";
private static final String PARAM_APPKEY = "&appKey=";
private static final String PARAM_SALT = "&salt=";
private static final String PARAM_SIGN = "&sign=";
/**
* 翻译方法,使用默认的翻译
* @param text
* @return
* @throws IOException
* @throws HttpException
* @throws JSONException
*/
public static TranslateResult transLate( String text) throws HttpException, IOException, JSONException{
return translate(text, Language.DEFAULT, Language.DEFAULT);
}
public static TranslateResult translate(String text,Language from,Language to) throws HttpException, IOException, JSONException{
/*拼装访问的url*/
StringBuffer urlBuffer = new StringBuffer(BASE_URL);
urlBuffer.append(PARAM_Q);
urlBuffer.append(text);
urlBuffer.append(PARAM_FROM);
urlBuffer.append(Language.getLanguage(from));
urlBuffer.append(PARAM_TO);
urlBuffer.append(Language.getLanguage(to));
urlBuffer.append(PARAM_APPKEY);
urlBuffer.append(APP_ID);
urlBuffer.append(PARAM_SALT);
int salt = random();
urlBuffer.append(salt);
urlBuffer.append(PARAM_SIGN);
String signFrom = APP_ID+text+salt+APP_KEY;
String sign = DigestUtils.md5Hex(signFrom);
urlBuffer.append(sign);
HttpClient client = new HttpClient();
GetMethod getMethod = new GetMethod(urlBuffer.toString());
client.executeMethod(getMethod);
String translateRsult = getMethod.getResponseBodyAsString();
JSONObject json = new JSONObject(translateRsult);
@SuppressWarnings("unchecked")
Iterator<String> keys = json.keys();
TranslateResult result = new TranslateResult();
while(keys.hasNext()){
String key = keys.next();
if(contains(TranslateResult.KEY,key)){
result.set(key, json.get(key));
}
}
System.out.println(result);
return result;
}
private static int random(){
Random random = new Random();
return random.nextInt(10);
}
public static <T> boolean contains(T[] os,T o){
return Arrays.asList(os).contains(o);
}
}