package tradutor;
import com.google.api.translate.Language;
import com.google.api.translate.Translate;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
System.out.println(“Saída usaGoogleAPI()”);
usaGoogleAPI();
System.out.println(“Saída usaGoogleWebPage()\n”);
usaGoogleWebPage();
}
public static void usaGoogleAPI(){
String textToTranslate = “HOW?”;
String textTranslated = null;
try{
Translate.setHttpReferrer(“http://localhost”);
textTranslated = Translate.execute(textToTranslate, Language.ENGLISH, Language.SPANISH);
if(textTranslated==null)
System.out.println(“Erro na tradução”);
else
System.out.println("\n" + textTranslated + “\n”);
}
catch(Exception e){
System.out.println("\nerro" + e.getMessage() + “\n”);;
}
}
public static void usaGoogleWebPage(){
String textToTranslate = “description”;
String textTranslated = new String();
String googleURL = “http://translate.google.com/translate_t?hl=en&ie=UTF-8&text=”;
googleURL += textToTranslate + “&sl=en&tl=pt”;
try{
URL url = new URL(googleURL);
URI uri = url.toURI();
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.addRequestProperty(“User-Agent”, “Mozilla/4.76”);
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), “UTF-8”));
String str = null;
while((str=bufferReader.readLine())!=null){
textTranslated += str;
}
System.out.println(textTranslated);
Pattern p = Pattern.compile("<span title="" + textToTranslate + “” onmouseover=“this.style.backgroundColor=’#ebeff9’” onmouseout=“this.style.backgroundColor=’#fff’”>");
Matcher m = p.matcher(textTranslated);
if(m.find()){
str = textTranslated.substring((textTranslated.lastIndexOf(m.pattern().toString())+m.pattern().toString().length()), textTranslated.length());
str = str.substring(0, str.indexOf("</span>"));
System.out.println(str);
}
else
System.out.println(“Sem tradução”);
bufferReader.close();
}catch(MalformedURLException e){
System.out.println(e.getMessage());
}catch(URISyntaxException e){
System.out.println(e.getMessage());
}catch(UnsupportedEncodingException e){
System.out.println(e.getMessage());
}catch(IOException e){
System.out.println(e.getMessage());
}
}
}
[quote=“GUJ”]Você é novo no GUJ? Vai criar um tópico e colar seu código-fonte? Leia aqui antes, por favor!
http://www.guj.com.br/posts/list/50115.java[/quote]
Use a tag [code ] para seu código ficar mais bem visto:
System.out.println("Assim.");