c# - WebClient 从 Google Translate API 返回无法识别的编码?

标签 c# .net encoding webclient google-translation-api

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

当我向它提供日文字符(例如テsuto中...)时,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 作为 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/

相关文章:

c# - 在 NuGet 配置中使用环境变量?

c# - Visual Studio 中的 TestContext - 它有什么作用?

c# - Elmah 将消息添加到通过调用 Raise(e) 记录的错误中

android - 在 Android axios (XMLHttpRequest) 上使用阿拉伯语和波斯语在 React Native 中损坏的字符

c# - 是否可以在没有 UWP 的情况下使用 .NET Native?

c# - 多线程,访问UI控制

c# - EF 转换问题

c# - 为什么 Parallel.Foreach 会创建无限线程?

c++ - Windows 游戏 : UTF-8, UTF-16、DirectX 和 Lua

python - 给定一个整数,它的 varint 编码有多大?