Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode in webclient unexpected result

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));
    }

And I want to see in "_stranslate "

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

but got this

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

Can some one help me?

like image 890
Likurg Avatar asked Dec 05 '22 17:12

Likurg


1 Answers

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

Content-Type => text/javascript; charset=KOI8-R

So just add this line.

client.Encoding = Encoding.GetEncoding(20866);

or

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

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

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);
like image 111
shriek Avatar answered Dec 10 '22 09:12

shriek