如何在 C# 中调用必应翻译函数
本文关键字:翻译 函数 调用 | 更新日期: 2023-09-27 18:35:31
我写了一个地铁风格的应用程序来调用必应翻译器,但它不起作用。我尝试调试此程序,但 UI 没有响应。我无法确定是我正在使用的URI还是其他问题。
这是我的代码:
public string GetTranslatedText(string textToTranslate, string fromLang, string toLang)
{
string translation;
if (fromLang != toLang)
{
string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=" +
appID + "&text=" + textToTranslate + "&from=" + fromLang + "&to=" + toLang;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
try
{
WebResponse response = request.GetResponse();
Stream strm = response.GetResponseStream();
StreamReader sr = new StreamReader(strm);
translation = sr.ReadToEnd();
response.Close();
sr.Close();
}
catch (WebException)
{
MessageBox.Show("Ensure that you are connected to the internet.",
"Translator", MessageBoxButton.OK, MessageBoxImage.Stop);
return (string.Empty);
}
}
else
{
MessageBox.Show("Will not translate to the same language.", "Translator",
MessageBoxButton.OK, MessageBoxImage.Exclamation);
return (string.Empty);
}
// Parse string into an XElement and get the XElement Value
// which is returned as the translated text.
return (XElement.Parse(translation).Value);
}
自四月起,您还需要访问令牌
http://msdn.microsoft.com/en-us/library/hh454950.aspx
您需要
将请求
发送到
https://api.microsofttranslator.com/v2/ajax.svc/TranslateArray2而不是
http://api.microsofttranslator.com/v2/Http.svc/Translate