Winform学习(7)–HttpWebRequest下载网页数据(包括意外情况解决办法)
首先,需要引用如下命名空间:
using System.Net;
再使用如下代码(格式非常固定):
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream, Encoding.GetEncoding("utf-8"));
string SourceCode = readStream.ReadToEnd();
response.Close();
readStream.Close();
意外情况(1)
有时调用GetResponseStream()方法时会出现如下错误:
System.Net.WebException:“远程服务器返回错误: (403) 已禁止。
此时可用如下解决方法:
//这是cookie问题
//在上述第一行和第二行之间插入
request.CookieContainer = new CookieContainer();
`
意外情况(2)
还有时会出现证书问题,解决方法如下:
using System.Security.Cryptography.X509Certificates;
private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
//添加如上代码后,继续在上述第一行代码前插入如下代码:
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;