Skip to content

Instantly share code, notes, and snippets.

@luketn
Last active August 21, 2018 10:06
Show Gist options
  • Save luketn/b71b37fc6cd4c3c0fe7574e29b20bda2 to your computer and use it in GitHub Desktop.
Save luketn/b71b37fc6cd4c3c0fe7574e29b20bda2 to your computer and use it in GitHub Desktop.
Java client to invoke the Google Translate API
package com.mycodefu;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Pattern;
public class GoogleTranslate {
public static void main(String[] args) throws IOException {
String translated = translate("yourapikeyhere", "en", "zh-CN", "hello");
System.out.println(translated);
}
public static String translate(String apiKey, final String sourceLanguage, final String targetLanguage, final String textToTranslate) throws IOException {
URL url;
BufferedReader reader = null;
StringBuilder stringBuilder;
try {
url = new URL("https://translation.googleapis.com/language/translate/v2?source=" + sourceLanguage + "&target=" + targetLanguage + "&format=text&q=" + textToTranslate + "&key=" + apiKey);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(15 * 1000);
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
return Pattern.compile(".*\"translatedText\":\\s?\"(.*?)\".*", Pattern.DOTALL).matcher(stringBuilder.toString()).replaceFirst("$1");
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment