- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用此链接: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/
我是一名优秀的程序员,十分优秀!