import java.util.ArrayList;
import com.google.api.translate.Language;
import com.google.api.translate.Translator;
public class Translation {
public static void main(String[] args) {
// Translate a single English String to French
Translator translator = new Translator();
System.out.println("Saying goodbye in French:");
System.out.println(translator.translate("goodbye", Language.ENGLISH, Language.FRENCH));
System.out.println();
}
}
答案 0 :(得分:2)
首先,Google翻译API是付费服务:https://cloud.google.com/pricing/
其次,您必须创建自己的API密钥并使用应用中的密钥:https://console.developers.google.com。
我正在使用的代码:
HttpTransport httpTransport = AndroidHttp.newCompatibleTransport();
AndroidJsonFactory jsonFactory = AndroidJsonFactory.getDefaultInstance();
Translate.Builder builder = new Translate.Builder(httpTransport, jsonFactory, null);
// need this, otherwise you get warning
builder.setApplicationName("Give a name");
Translate translate = builder.build();
List<String> list = new ArrayList<String>();
// I only add one char to the list
list.add(String.valueOf(word[0]));
Translate.Translations.List request = translate.translations().list(list, "en").setKey("<your_api_key>");
String result = request.execute().getTranslations().get(0).getTranslatedText();
注意:暂时还不知道原因,如果我使用Android API密钥,我总会得到同样的错误:&#34; com.google.api.client.googleapis.json.GoogleJsonResponseException:403 Forbidden&# 34;,并且原因说&#34; ipRefererBlocked&#34;,但是如果我使用我的浏览器密钥则没问题。希望其他人能找出原因。