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