Google翻译API问题

时间:2011-09-02 10:16:23

标签: java google-translate google-translation-api

我需要一个使用Google Translation API将西班牙语转换为英语的示例。我尝试使用以下代码。它给出了一些例外。有人可以帮助我。

代码:

import  com.google.api.translate.*;
public class GoogleTranslator {

    /**
     * @param args

    */
    @SuppressWarnings("deprecation")
    public static void main(String[] args) {// TODO code application logic here


            try {
                Translate.setHttpReferrer("sp-en");
                String translatedText = Translate.translate("Hola mundo", Language.SPANISH, Language.ENGLISH);
                System.out.println(translatedText);
                } catch (Exception ex) {
                ex.printStackTrace(); }

    }
}

错误:

java.lang.Exception: [google-api-translate-java] Error retrieving translation.
    at com.google.api.GoogleAPI.retrieveJSON(GoogleAPI.java:136)
    at com.google.api.translate.Translate.execute(Translate.java:69)
    at com.google.api.translate.Translate.translate(Translate.java:192)
    at GoogleTranslator.main(GoogleTranslator.java:15)
Caused by: java.net.UnknownHostException: ajax.googleapis.com
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at sun.net.NetworkClient.doConnect(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.<init>(Unknown Source)
    at sun.net.www.http.HttpClient.New(Unknown Source)
    at sun.net.www.http.HttpClient.New(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
    at com.google.api.GoogleAPI.retrieveJSON(GoogleAPI.java:115)
    ... 3 more

3 个答案:

答案 0 :(得分:1)

您需要找出无法访问此主机的原因:ajax.googleapis.com

例外情况说:

 java.net.UnknownHostException: ajax.googleapis.com 

javadoc表示抛出UnknownHostException以指示无法确定主机的IP地址。

您应该使用DNS。

  

nslookup ajax.googleapis.com

答案 1 :(得分:0)

将您的DNS设置为google one

如果在linux机器上

sudo gedit /etc/resolv.conf

添加

nameserver 8.8.8.8
nameserver 8.8.4.4

或者如果在Windows上转到网络设置并为活动连接设置DNS

答案 2 :(得分:0)

你没有api密钥,例如GoogleAPI.setKey();你需要这样的东西继续我猜