以下代码:
var text = (new WebClient()).DownloadString("http://export.arxiv.org/api/query?search_query=au:Freidel_L*&start=0&max_results=20"));
生成一个变量text
,其中包含字符串等内容
"$κ$-Minkowski space, scalar field, and the issue of Lorentz invariance"
但是,当我在 Firefox 中访问该 URL 时,我得到了
$κ$-Minkowski space, scalar field, and the issue of Lorentz invariance
这实际上是正确的。我也尝试过
var data = (new WebClient()).DownloadData("http://export.arxiv.org/api/query?search_query=au:Freidel_L*&start=0&max_results=20");
var text = System.Text.UTF8Encoding.Default.GetString(data);
但这也带来了同样的问题。
我不确定问题出在哪里。提要是否谎称是 UTF8 编码的,并且浏览器足够聪明,可以识别出这一点,但 WebClient
却不能?提要是否已正确进行 UTF8 编码,但 WebClient
因其他原因而失败?我可以采取什么措施来缓解这种情况?
最佳答案
这不是说谎。在调用 DownloadString 之前,您应该先设置 Web 客户端的编码。
using(WebClient webClient = new WebClient())
{
webClient.Encoding = Encoding.UTF8;
string s = webClient.DownloadString("http://export.arxiv.org/api/query?search_query=au:Freidel_L*&start=0&max_results=20");
}
至于为什么你的替代方案不起作用,是因为用法不正确。它应该是:
System.Text.Encoding.UTF8.GetString()
关于.net - 由于编码问题,WebClient.DownloadString 导致字符损坏,但浏览器正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7137165/