|
和上一话所说的利用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的代码,转载需保留来源!
郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。