Last time I talked about using ASP, PHP, and C# to implement Google Translate and develop an API (Tags: Google Translate API). Since a lot of program code is implemented in JAVA (JSP), I still used some time to make a java version. I am still a beginner in JAVA. During this period, I checked some information. Although the program is relatively short, it is still quite naughty.
As mentioned in the previous chapter, using JAVA to obtain the content of the URL, the technology in this article implements the acquisition, and then regularizes the matching results, and it is complete. Look at the code:
//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;
}
http://bizhi.downcodes.com
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); //Match the first item
}
return null;
}
public static void main(String[] args){
GoogleTranslator obj=new GoogleTranslator();
System.out.println(obj.GetText("cjjer is a Java genius"));
}
};
Then save as GoogleTranslator.java and use:
javac GoogleTranslator.java -encoding utf-8
After compiling, just use JAVA.