编码在Web客户端意外的结果 [英] Encode in webclient unexpected result

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

问题描述

我尝试使用Web客户端,以词'香蕉'翻译成俄文

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 "

{句子:[{反:Банан,原稿:香蕉@,TRANSLIT:巴南@,src_translit :}],SRC:恩,server_time:0}

{"sentences":[{"trans":"Банан","orig":"Banana@","translit":"Banan @","src_translit":""}],"src":"en","server_time":0}

但得到这个

{句子:[{反:вБОБО,原稿:香蕉@,TRANSLIT:巴南@ ,src_translit:}],SRC:恩,server_time:0}

{"sentences":[{"trans":"вБОБО","orig":"Banana@","translit":"Banan @","src_translit":""}],"src":"en","server_time":0}

可以将部分一个可以帮助我?

Can some one help me?

推荐答案

尝试检查响应头,内容类型的告诉你,你应该使用什么编码。

Try checking the response headers, the content types tells you what encoding you should use.

的Content-Type =>文/ JavaScript的;字符集= KOI8-R

所以才加入这一行。

client.Encoding = Encoding.GetEncoding(20866);

client.Encoding = Encoding.GetEncoding("KOI8-R");

有关编码的完整列表可为的Encoding类

A complete list for encodings can be found in the documentation for the Encoding Class

另一种方法是只使用 System.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);

这篇关于编码在Web客户端意外的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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