C# WebClient DownloadString 返回乱码

4

我试图使用以下代码查看http://simpledesktops.com/browse/desktops/2012/may/17/where-the-wild-things-are/的源代码:

String URL = "http://simpledesktops.com/browse/desktops/2012/may/17/where-the-wild-things-are/";

WebClient webClient = new WebClient();

webClient.Headers.Add("user-agent", "Mozilla/5.0 (Windows; Windows NT 5.1; rv:1.9.2.4) Gecko/20100611 Firefox/3.6.4");
webClient.Encoding = Encoding.GetEncoding("Windows-1255");

string download = webClient.DownloadString(URL);

webClient.Dispose();

Console.WriteLine(download);

当我运行这个程序时,控制台返回了一堆看起来像解码错误的无意义信息。
我还尝试添加头文件,但没有成功。
webClient.Headers.Add("user-agent", "Mozilla/5.0 (Windows; Windows NT 5.1; rv:1.9.2.4) Gecko/20100611 Firefox/3.6.4");    
webClient.Headers.Add("Accept-Encoding", "gzip,deflate");

其他网站都返回了正确的html源代码。我也可以通过Chrome查看页面源代码。这是怎么回事呢?

响应已经被gzip压缩,您需要解压它,请参考https://dev59.com/DnA85IYBdhLWcg3wCe9Z - Antonio Bakula
你如何知道响应是Windows-1255编码? - Cole Tobin
2个回答

4

该URL的响应已经被压缩,您需要对其进行解压或设置空的Accept-Encoding头部,不需要使用user-agent字段。

  String URL = "http://simpledesktops.com/browse/desktops/2012/may/17/where-the-wild-things-are/";    
  WebClient webClient = new WebClient();    
  webClient.Headers.Add("Accept-Encoding", "");
  string download = webClient.DownloadString(URL);

1
今天我也遇到了同样的问题。使用WebClient对象检查URL是否返回结果。但我的经验不同。我尝试删除Accept-Encoding,基本上使用@Antonio Bakula在他的答案中给出的代码。但每次都会收到相同的错误(InvalidOperationException)。所以这个方法没有起作用:
WebClient wc = new WebClient();
wc.Headers.Add("Accept-Encoding", "");
string result = wc.DownloadString(url);

但是将“任何”文本作为用户代理添加确实起到了作用。这个方法很好用:
WebClient wc = new WebClient();
wc.Headers.Add(HttpRequestHeader.UserAgent, "My User Agent String");
System.IO.Stream stream = wc.OpenRead(url);

显然,你的结果可能会有所不同。还需要注意的是,我正在使用ASP.NET 4.0.30319。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接