谷歌翻译错误

时间:2011-10-13 07:42:04

标签: c# google-translate

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

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;
    }

1 个答案:

答案 0 :(得分:2)

您要么遇到一些Google设置的API使用限制(请参阅http://code.google.com/apis/language/translate/v2/getting_started.html

OR

问题在于您正在使用的语言(ur = Urdu?)...您应该通过相应的API检查此组合是否实际可用。如果你真的想要西班牙语,你的评论建议我怀疑是es

另一点:
您没有转义您的网址参数(尤其是要翻译的文字),这反过来可能导致将来出现一些问题......

相关问题