2011-09-02 293 views
0

我需要一個例子,使用谷歌翻譯API將西班牙語翻譯成英語。我試着用下面的代碼。它給出了一些例外。有人可以幫助我一樣。谷歌翻譯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 
+0

http://code.google.com/p/google-api-translate-java/issues/detail?id=52 –

+0

嘗試ping服務器。我可以從這裏看到它。 –

回答

1

你需要弄清楚爲什麼你沒有達到這個主持人:ajax.googleapis.com

除外說:

java.net.UnknownHostException: ajax.googleapis.com 

javadoc表示拋出UnknownHostException以指示無法確定主機的IP地址。

你應該你的DNS。

NSLOOKUP ajax.googleapis.com

0

設置你的DNS給Google

如果Linux機器上

sudo gedit /etc/resolv.conf

添加

nameserver 8.8.8.8 
nameserver 8.8.4.4 

或者如果在windows上轉到網絡設置並設置DNS爲活動連接

0

您沒有API密鑰,例如GoogleAPI.setKey();你需要這樣的事情繼續我猜