|
和上一話所說的利用Java獲取URL的內容,這篇的技術實現獲取,然后正則匹配結果,就完成了。看代碼:
復制代碼 代碼如下:
//Javac GoogleTranslator.Java -encoding utf-8
import Java.io.InputStream;
import Java.NET.URLEncoder;
import Java.util.regex.*;
public class GoogleTranslator{
public String getUrlContent(String path){
String rtn = "";
int c;
try{
Java.NET.URL l_url = new Java.NET.URL(path);
Java.NET.HttpURLConnection l_connection = (Java.NET.HttpURLConnection) l_url.openConnection();
l_connection.setRequestProperty("User-agent","Mozilla/4.0");
l_connection.connect();
InputStream l_urlStream = l_connection.getInputStream();
while (( ( c= l_urlStream.read() )!=-1)){
int all=l_urlStream.available();
byte[] b =new byte[all];
l_urlStream.read(b);
rtn+= new String(b, "UTF-8");
}
//Thread.sleep(2000);
l_urlStream.close();
}catch(Exception e){
e.printStackTrace();
}
return rtn;
}
public String GetText(String Src){
String Os=null;
try{
String pUrl="http://translate.google.com/translate_t?langpair="+URLEncoder.encode("zh-CN|en","utf-8")+"&text="+URLEncoder.encode(Src,"gb2312") ;
String pageContent =getUrlContent(pUrl);
if(!isNullOrEmpty(pageContent)){
Os= GetMatchString(pageContent,"(<div id=result_box dir=/"ltr/">)([?://s//S]*?)</div>",2);
}
}catch(Exception e){
e.printStackTrace();
}
return Os;
}
private boolean isNullOrEmpty(String param) {
return param == null || param.trim().length() == 0;
}
public String GetMatchString(String text,String pattern,int point){
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
if(m.find()) {
return m.group(point); //匹配第1項
}
return null;
}
public static void main(String[] args){
GoogleTranslator obj=new GoogleTranslator();
System.out.println(obj.GetText("cjjer是Java天才"));
}
};
然后保存為GoogleTranslator.Java,然后使用:
復制代碼 代碼如下:
Javac GoogleTranslator.Java -encoding utf-8
編譯了,然后Java一下就可以了。
jsp技術:JAVA (Jsp)利用Google的Translate開發API的代碼,轉載需保留來源!
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。