gpt4 book ai didi

c# - 在 webclient 中编码意外结果

转载 作者:太空狗 更新时间:2023-10-30 00:01:50 35 4
gpt4 key购买 nike

我尝试使用 webclient 将单词“Banana”翻译成 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”中看到

{"sentences":[{"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}

谁能帮帮我?

最佳答案

尝试检查响应 header ,内容类型告诉您应该使用哪种编码。

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

所以只需添加这一行。

client.Encoding = Encoding.GetEncoding(20866);

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

编码的完整列表可以在 Encoding Class 的文档中找到

另一种方法是只使用 System.Net.Mime.ContentType获取字符集。像这样:

byte[] data = client.DownloadData(url);
ContentType contentType = new System.Net.Mime.ContentType(client.ResponseHeaders[HttpResponseHeader.ContentType]);
string _stranslate = Encoding.GetEncoding(contentType.CharSet).GetString(data);

关于c# - 在 webclient 中编码意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10043590/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com