Since many program codes are implemented by JAVA (JSP), I made a java version using a little time. I am still getting started with JAVA. During this period, I checked some information, although the program is relatively short, it is still relatively naughty.
As mentioned above, JAVA is used to obtain the URL content. This technology is used to obtain the content, and then the regular expression matching result is complete. Check the Code:
Copy codeThe Code is as follows:
// 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 ();
Rochelle connection.setrequestproperty ("User-agent", "Mozilla/4.0 ");
Rochelle 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); // match 1st items
}
Return null;
}
Public static void main (String [] args ){
GoogleTranslator obj = new GoogleTranslator ();
System. out. println (obj. GetText ("cjjer is a Java genius "));
}
};
Save it as GoogleTranslator. java and then use:
Copy codeThe Code is as follows:
Javac GoogleTranslator. java-encoding UTF-8
Compiled, and then JAVA is enough.