C#登录https网站并下载文件

.net很久没用了,最近要做个小工具下载一个https的内容,想来想去还是.net的环境最方便。java要装jdk,python也要python的环境,php有php的环境。

主要功能代码都从网上收集,这里记录一些片段,用作备份。

1.登录https

            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受
        }
本来想着https的连接需要证书的,原来还可以跳过证书的验证,直接返回true就行了,实践证明可以连接成功。HTTPS连接最初的若干毫秒

2.继续访问

完成登录后,要保持这个session,查看response.Headers["Set-Cookie"],可以看到cookie里的session信息,只要把这些cookie内容在下一次请求时带上就行了。

请求时cookie的转换代码:

            string cookieString = response.Headers["Set-Cookie"];
            CookieCollection cookies = new CookieCollection();
            Regex re = new Regex("([^;,]+)=([^;,]+); path=([^;,]+); expires=([^;,]+)", RegexOptions.IgnoreCase);//视具体内容进行调整
            foreach (Match m in re.Matches(cookieString))
            {
                Cookie c = new Cookie(m.Groups[1].Value, m.Groups[2].Value);
                c.Domain = "yourDomain";//放你要访问网站的域名
                cookies.Add(c);
            }

3.下载文件

请求的是一个下载链接,另存为的文件名,在response.Headers里。通过字符串操作把它提取出来。

文件内容要通过流的方式,把它读出来,保存成文件。

Stream stream = response.GetResponseStream();
FileStream fs = new FileStream(file, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
BinaryReader br = new BinaryReader(stream);

byte[] nbytes = new byte[2048];
int nReadSize = 0;
nReadSize = br.Read(nbytes, 0, 2048);
while (nReadSize > 0)
{
      bw.Write(nbytes, 0, nReadSize);
      nReadSize = br.Read(nbytes, 0, 2048);
}
bw.Close();
br.Close();