我正在构建一个应用程序来访问Google Translate for Windows Phone。我注意到,对于翻译后的单词将包含外来字符的语言,文本框会全部搞砸,而是显示随机符号等。不知道为什么。我是否需要在文本框中启用某些内容?
代码:
private void btnTranslate_Click(object sender, RoutedEventArgs e)
{
string text = txtboxOriginal.Text;
string fromLanguage;
string toLanguage;
//Use Bing.
if ((bool)settings["translateIsBing"] == true)
{
if (string.IsNullOrWhiteSpace(text))
{
MessageBox.Show("Can't translate with nothing to translate. Please try again.");
}
else
{
}
}
//Use Google.
else if ((bool)settings["translateIsGoogle"] == true)
{
if (string.IsNullOrWhiteSpace(text))
{
MessageBox.Show("Can't translate with nothing to translate. Please try again.");
}
else
{
fromLanguage = this.getLanguageCodeGoogle(lstOriginalLanguages.SelectedIndex.ToString());
toLanguage = this.getLanguageCodeGoogle(lstTranslateToLanguages.SelectedIndex.ToString());
string url = "http://translate.google.com/translate_t?text=" + text + "&sl=" + fromLanguage + "&tl=" + toLanguage;
WebClient webclient = new WebClient();
webclient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webclient_DownloadStringCompleted);
webclient.DownloadStringAsync(new Uri(url, UriKind.RelativeOrAbsolute));
}
}
}
void webclient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
try
{
Debug.WriteLine(e.Result);
string result = e.Result;
int startPosition = result.IndexOf("TRANSLATED_TEXT='");
int length = result.IndexOf(@"';INPUT") - startPosition;
string partial = result.Substring(startPosition, length);
Debug.WriteLine("Step 1: {0}", partial);
startPosition = partial.IndexOf("'") + 1;
length = partial.Length - startPosition;
string secondPartial = partial.Substring(startPosition, length);
Debug.WriteLine("Step 2: {0}", secondPartial);
translatedText = secondPartial;
txtboxOriginal.Text = secondPartial;
btnTranslate.Content = "Translated";
btnTranslate.IsEnabled = false;
btnCopy.Visibility = Visibility.Visible;
btnCopy.IsEnabled = true;
btnReset.Visibility = Visibility.Visible;
btnReset.IsEnabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
答案 0 :(得分:0)
问题可能来自Google的回复编码类型。 当您查看响应的Content-type时,它始终不是UTF8,WebClient.DownloadStringAsync将其解码为哪个,因此您必须更改解码类型
您必须更改Webclient.Encoding
以匹配请求类型
可以找到问题的解决方案here