在webclient中编码意外结果 [英] Encode in webclient unexpected result
问题描述
我尝试使用webclient将Banana翻译成rus
I try use webclient to translate word 'Banana' into rus
private void button1_Click(object sender, EventArgs e)
{
Navigate("http://translate.google.ru/translate_a/t?client=x&text=Banana&hl=en&sl=en&tl=ru");
}
private void Navigate(String address)
{
WebClient client = new WebClient();
client.Proxy = WebRequest.DefaultWebProxy;
client.Credentials = new NetworkCredential("user", "password", "domain");
client.Proxy.Credentials = new NetworkCredential("user", "password", "domain");
string _stranslate = client.DownloadString(new Uri(address));
}
我想在_stranslate中看到
And I want to see in "_stranslate "
{句子:[{trans:Банан,orig:Banana @,translit:Banan @,src_translit :}],src:en,server_time:0}
{"sentences":[{"trans":"Банан","orig":"Banana@","translit":"Banan @","src_translit":""}],"src":"en","server_time":0}
>
but got this
{句子:[{trans:вБОБО,orig:Banana @,translit ,src_translit:}],src:en,server_time:0}
{"sentences":[{"trans":"вБОБО","orig":"Banana@","translit":"Banan @","src_translit":""}],"src":"en","server_time":0}
一个帮助我?
推荐答案
尝试检查响应头,内容类型告诉你应该使用什么编码。
Try checking the response headers, the content types tells you what encoding you should use.
Content-Type =>文/ JavaScript的; charset = KOI8-R
所以只需添加一行。
client.Encoding = Encoding.GetEncoding(20866);
或
client.Encoding = Encoding.GetEncoding("KOI8-R");
编码的完整列表可以在编码类
A complete list for encodings can be found in the documentation for the Encoding Class
另一种方式将只是使用 系统。 Net.Mime.ContentType
获取字符集。
像这样:
Another way would be to just use System.Net.Mime.ContentType
to get the charset.
Like this:
byte[] data = client.DownloadData(url);
ContentType contentType = new System.Net.Mime.ContentType(client.ResponseHeaders[HttpResponseHeader.ContentType]);
string _stranslate = Encoding.GetEncoding(contentType.CharSet).GetString(data);
这篇关于在webclient中编码意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!