gpt4 book ai didi

c# - WebClient 从 Google Translate API 返回身份不明的编码?

转载 作者:行者123 更新时间:2023-11-30 23:02:44 26 4
gpt4 key购买 nike

我正在使用此链接:https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=en&dt=t&q=myTextHere

当我向它输入日文字符(如テスト中...)时,DownloadString 方法会返回奇怪的字符,例如:ム† ã,¹ãƒä¸ ...

正确的字符串应该是“Under Test...”

您可以点击浏览器上的链接亲自查看:https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=en&dt=t&q=テスト中

我尝试了多种方法,例如将客户端的编码设置为 UTF-8 并使用 HttpUtility.UrlEncode(myText) 但我无法获得浏览器返回的内容。将 DownloadString 替换为 DownloadFile as txt 会返回相同的错误文本。如何获得与浏览器相同的结果?

这是一个类似于我的环境的小代码片段:

String s = "テスト中";
Console.WriteLine("src="+s);
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
string downloadString = @client.DownloadString("https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=en&dt=t&q=" + HttpUtility.UrlEncode(s));
Console.WriteLine("data:{\n"+downloadString+"\n}");

最佳答案

我完全不知道为什么 Google Translate API 会返回乱码。格式错误的 WebClient 响应包括“fr”而不是“ja”,表明 API 将您的文本错误解释为法语 (!) 而不是日语。或者什么的。

无论如何,经过一些实验后我发现,如果您设置 User-Agent header ,API 会正常运行:

WebClient client = new WebClient();
client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
client.Encoding = Encoding.UTF8;
string downloadString = client.DownloadString("https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=en&dt=t&q=" + HttpUtility.UrlEncode(s));
// Result: [[["Under test","テスト中",null,null,3]],null,"ja",...]

关于c# - WebClient 从 Google Translate API 返回身份不明的编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50322324/

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