由於Google translate API要收 ,因此想了一 偷 的方法
1. 用HttpClient 送一 request http://translate.google.com
2. 再用Jsoup parse html, 取出翻 後的文字
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.MessageFormat;
import org.apache.commons.io.IOUtils;
import org.bb.util.net.http.HttpClientUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
/**
* TranslateUtil
*
* <pre>翻 工具
* PS: 透 google translate
* </pre>
*
* @author catty
* @version 1.0, Created on 2011/9/2
*/
public class TranslateUtil {
protected static final String URL_TEMPLATE = "http://translate.google.com/?langpair={0}&text={1}";
protected static final String ID_RESULTBOX = "result_box";
protected static final String ENCODING = "UTF-8";
protected static final String AUTO = "auto"; // google自 判 源 系
protected static final String TAIWAN = "zh-TW"; // 繁中
protected static final String CHINA = "zh-CN"; // 中
protected static final String ENGLISH = "en"; // 英
protected static final String JAPAN = "ja"; // 日
/**
* <pre>Google翻
* PS: 交由google自 判 源 系
* </pre>
*
* @param text
* @param target_lang 目 系
* @return
* @throws Exception
*/
public static String translate(final String text, final String target_lang) throws Exception {
return translate(text, AUTO, target_lang);
}
/**
* <pre>Google翻 </pre>
*
* @param text
* @param src_lang 源 系
* @param target_lang 目 系
* @return
* @throws Exception
*/
public static String translate(final String text, final String src_lang, final String target_lang)
throws Exception {
InputStream is = null;
Document doc = null;
Element ele = null;
try {
// create URL string
String url = MessageFormat.format(URL_TEMPLATE,
URLEncoder.encode(src_lang + "|" + target_lang, ENCODING),
URLEncoder.encode(text, ENCODING));
// connect & download html
is = HttpClientUtil.downloadAsStream(url);
// parse html by Jsoup
doc = Jsoup.parse(is, ENCODING, "");
ele = doc.getElementById(ID_RESULTBOX);
String result = ele.text();
return result;
} finally {
IOUtils.closeQuietly(is);
is = null;
doc = null;
ele = null;
}
}
/**
* <pre>Google翻 : 中-->繁中</pre>
*
* @param text
* @return
* @throws Exception
*/
public static String cn2tw(final String text) throws Exception {
return translate(text, CHINA, TAIWAN);
}
/**
* <pre>Google翻 : 繁中-->