package com.eg.android.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.json.JSONObject;
import android.util.Log;
public class Translate {
private static final String TAG = "Translate";
private static final String ENCODING = "UTF-8";
private static final String TRANS_URL = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=";
private static final String LANGPAIR_TEXT = "&langpair=";
private static final String LANGPAIR_SEPARTOR = "%7C";
public static String retrieveTranslation(String text, String from, String to) {
String result = null;
HttpURLConnection conn = null;
try {
StringBuilder strBuilder = new StringBuilder();
String url = strBuilder.append(TRANS_URL)
.append(URLEncoder.encode(text, ENCODING))
.append(LANGPAIR_TEXT).append(from)
.append(LANGPAIR_SEPARTOR).append(to).toString();
Log.d(TAG, "Connecting to " + url);
conn = (HttpURLConnection) new URL(url).openConnection();
String respStr = getResponseString(conn.getInputStream());
JSONObject json = new JSONObject(respStr);
result = ((JSONObject) json.get("responseData"))
.getString("translatedText");
} catch (Exception e) {
Log.e(TAG, "translation fail!!");
} finally {
try {
if(conn != null) {
conn.getInputStream().close();
if (conn.getErrorStream() != null)
conn.getErrorStream().close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
private static String getResponseString(InputStream inputStream) {
StringBuilder outputBuilder = new StringBuilder();
BufferedReader reader = null;
try {
String str = null;
if (inputStream != null) {
reader = new BufferedReader(new InputStreamReader(inputStream,
ENCODING));
while ((str = reader.readLine()) != null) {
outputBuilder.append(str);
}
}
} catch (Exception e) {
Log.e(TAG,"[google-api-translate-java] Error reading translation stream.");
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return outputBuilder.toString();
}
}
String res = Translate.retrieveTranslation("将这行中文翻译为英文", "zh-CN", "en");