如何使用 WebRequest 访问使用 HTTPS 的 SSL 加密站点? [英] How do I use WebRequest to access an SSL encrypted site using HTTPS?

查看:53
本文介绍了如何使用 WebRequest 访问使用 HTTPS 的 SSL 加密站点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个从用户提供的 URL 读取内容的程序.我的问题出在这样的代码中:

I'm writing a program that reads content from a user provided URL. My problem is in the code that goes something like this:

Uri uri = new Uri(url);
WebRequest webRequest = WebRequest.Create(uri);
WebResponse webResponse = webRequest.GetResponse();
ReadFrom(webResponse.GetResponseStream());

如果提供的 url 是一个 https:// URL,这将是破坏性的.任何人都可以帮助我更改此代码,以便它可以与 SSL 加密内容一起使用.谢谢.

And this is breaking if the provided url is an https:// URL. Can anyone help me with changing this code so that it will work with SSL encrypted content. Thanks.

推荐答案

您的做法是正确的,但用户可能会向安装了无效 SSL 证书的站点提供 URL.如果在发出实际 Web 请求之前输入此行,则可以忽略这些证书问题:

You're doing it the correct way but users may be providing urls to sites that have invalid SSL certs installed. You can ignore those cert problems if you put this line in before you make the actual web request:

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

其中 AcceptAllCertifications 定义为

public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    return true;
}

这篇关于如何使用 WebRequest 访问使用 HTTPS 的 SSL 加密站点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆