2011-10-13 110 views
2

我在使用Google翻译API V2时遇到了异常。异常文本是“远程服务器返回错误:(403)禁止”。调用req.GetResponse()函数时发生异常。我正在使用以下代码。请提及是否有任何正确的代码可用。 感谢Google翻译错误

public static string Translate() 
    { 
     String textToTranslate = "Common"; 
     String fromLanguage = "en"; // english 
     String toLanguage = "ur"; // spanish 
     String apiKey = /*My API Key*/; 

     // create the url for making web request 
     String apiUrl = "https://www.googleapis.com/language/translate/v2?key={0}&source={1}&target={2}&q={3}"; 
     String url = String.Format(apiUrl, apiKey, fromLanguage, toLanguage, textToTranslate);  
     string text = string.Empty; 

     try 
     { 
      // create the web request 
      WebRequest req = HttpWebRequest.Create(url); 

      // set the request method 
      req.Method = "GET"; 

      // get the response 
      using (WebResponse res = req.GetResponse()) 
      { 
       // read response stream 
       // you must specify the encoding as UTF8 
       // because google returns the response in UTF8 format 
       using (StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8)) 
       { 
        // read text from response stream 
        text = sr.ReadToEnd(); 
       } 
      } 
     } 
     catch (Exception e) 
     { 
      throw; // throw the exception as is/ 
     } 

     // return text to callee 
     return text; 
    } 

回答

2

要么你会碰到一些谷歌设定的API使用限制(见http://code.google.com/apis/language/translate/v2/getting_started.html

OR

问题在于语言(ur =乌尔都语?)你正在使用.. 。你应该检查这个组合是否真的可以通过相应的API获得。如果你真的想要西班牙语作为你的评论建议,我怀疑这将是es

还有一点:
你是不是逃避你的URL参数(ESP文本进行翻译。)这反过来又可能导致在未来的一些问题...