C#中使用Webclient获取页面资源
Use Webclient to get page resource in C#
我使用下面的代码获取页面源代码,但它没有 return 属性 数据 :
string url = "http://www.tsetmc.com/Loader.aspx?ParTree=15131F";
WebClient client = new WebClient();
client.Headers["Accept-Encoding"] = "gzip";
string pageSource = client.DownloadString(url);
网站内容编码为gzip
通过设置 client.Headers["Accept-Encoding"] = "gzip";
,您要求服务器发送压缩响应。但是,您没有解压缩它。这导致了不正确的响应。
根据 ,您可以 WebClient
通过修改它创建的 HttpWebRequest
来自动解压缩响应:
class MyWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
var request = (HttpWebRequest) base.GetWebRequest(address);
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
return request;
}
}
string url = "http://www.tsetmc.com/Loader.aspx?ParTree=15131F";
WebClient client = new MyWebClient();
// don't set the Accept-Encoding header here; it will be done automatically
string pageSource = client.DownloadString(url);
我使用下面的代码获取页面源代码,但它没有 return 属性 数据 :
string url = "http://www.tsetmc.com/Loader.aspx?ParTree=15131F";
WebClient client = new WebClient();
client.Headers["Accept-Encoding"] = "gzip";
string pageSource = client.DownloadString(url);
网站内容编码为gzip
通过设置 client.Headers["Accept-Encoding"] = "gzip";
,您要求服务器发送压缩响应。但是,您没有解压缩它。这导致了不正确的响应。
根据 ,您可以 WebClient
通过修改它创建的 HttpWebRequest
来自动解压缩响应:
class MyWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
var request = (HttpWebRequest) base.GetWebRequest(address);
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
return request;
}
}
string url = "http://www.tsetmc.com/Loader.aspx?ParTree=15131F";
WebClient client = new MyWebClient();
// don't set the Accept-Encoding header here; it will be done automatically
string pageSource = client.DownloadString(url);