在webclient中编码意外结果 [英] Encode in webclient unexpected result

查看:115
本文介绍了在webclient中编码意外结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆