SoFunction
Updated on 2025-03-10

JAVA (Jsp) Code to develop API using Google's Translate


//javac -encoding utf-8
import ;
import ;
import .*;
public class GoogleTranslator{
public String getUrlContent(String path){
String rtn = "";
int c;
try{
l_url = new (path);
l_connection = () 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");
}
//(2000);
l_urlStream.close();
}catch(Exception e){
();
}
return rtn;
}
public String GetText(String Src){
String Os=null;
try{
String pUrl="/translate_t?langpair="+("zh-CN|en","utf-8")+"&text="+(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){
();
}
return Os;
}
private boolean isNullOrEmpty(String param) {
return param == null || ().length() == 0;
}
public String GetMatchString(String text,String pattern,int point){
Pattern p = (pattern);
Matcher m = (text);
if(()) {
return (point); //Match item 1
}
return null;
}
public static void main(String[] args){
GoogleTranslator obj=new GoogleTranslator();
(("cjjer is a Java genius"));
}
};