开发者

Google translation error

I am facing an exception while using Google translation API V2. Exception text is "The remote server returned an error: (403) Forbidden". Exception occurs when req.GetResponse()function called. I am using following code. Please mention if any correct code is available. Thanks

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


You either run into some Google-set API usage limit (see http://code.google.com/apis/language/translate/v2/getting_started.html)

OR

The problem lies in the language (ur = Urdu ?) you are using... you should check whether this combination is actually available via the respective API. If you really want spanish as your comment suggests I suspect that would be es.

Another point:
You are not escaping your URL parameters (esp. the text to be translated) which in turn could lead to some problems in the future...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜