1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| public class GoogleTranslate
{
String RequeteBuffer = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&hl=fr&q=%s&langpair=%s|%s";
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
// OutputStream sf = new ByteOutputStream();
GoogleTranslate gt = new GoogleTranslate();
String buffer = gt.Get("debut de la fonction d'optimisation", "fr", "en");
System.err.println(""+buffer);
buffer = gt.Get("Debut de la fOnction d'optimisation", "fr", "en");
System.err.println(""+buffer);
buffer = gt.Get("Debut de la fonction d'optimisation", "fr", "en");
System.err.println(""+buffer);
buffer = gt.Get("Début de la fonction d'optimisation", "fr", "en");
System.err.println(""+buffer);
buffer = gt.Get("Début de la fonction d'optimisation", "fr", "en");
System.err.println(""+buffer);
}
@SuppressWarnings("deprecation")
public String Get(String phraseatraduire, String langue1, String langue2) throws Exception {
String flag = "translatedText\":";
String responseFlag = "\"responseStatus\": 200";
phraseatraduire = StringOperation.sansAccent(phraseatraduire);
String req = RequeteBuffer;
req=String.format(RequeteBuffer, URLEncoder.encode(phraseatraduire), langue1, langue2);
URL yahoo = new URL(req);
BufferedReader in = new BufferedReader(new InputStreamReader(yahoo.openStream()));
String inputLine;
String buffer = "";
while ((inputLine = in.readLine()) != null)
buffer+=inputLine;
in.close();
if (buffer.contains(responseFlag)==false)
throw new Exception("Probleme le serveur reponds "+buffer);
// Cherche la reponse
int idx = buffer.indexOf(flag);
if (idx == -1) throw new Exception("Probleme ne trouve pas le flag "+flag+" dans la reponse : "+buffer);
idx += flag.length()+1;
int idx2 = buffer.indexOf("\"", idx);
buffer = buffer.substring(idx, idx2);
return buffer;
}
} |
Partager