c# - 使用带有 HTTPS 证书的 System.Net.WebClient

标签 c# https httpwebrequest certificate http-post

在我的 C# Windows 客户端中,我有一个 POST 提交到“母舰”。当然,我希望提交的数据得到保护,所以我支付了 HostGator 的费用来给我颁发 SSL 证书。

我保存了 .CER 文件,并且正在构建请求:

//wrapper for WebClient object to use certificate file
class SecureWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri address)
    {
        HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
        string certPath = @"e:\mycertificate.cer";
        X509Certificate myCert = X509Certificate.CreateFromCertFile(certPath);
        request.ClientCertificates.Add(myCert);
        return request;
    }
}

//request
private static SecureWebClient client = new SecureWebClient();
private static NameValueCollection = new NameValueCollection();
nvc.Add(POST_ACTION, ACTION_CODE_LOGIN);
nvc.Add(POST_EMAIL, email);
nvc.Add(POST_PASSWORD, password);

sResponse = System.Text.Encoding.ASCII.GetString(client.UploadValues(BASE_URL + ACTION_PAGE, nvc));

它抛出 System.Net.WebException:

The underlying connection was closed: An unexpected error occurred on a send.

InnerException 是一个 System.IO.IOException:

The handshake failed due to an unexpected packet format.

对我做错了什么有任何见解吗?

最佳答案

如果您使用客户端证书并且您可以使用https://访问您的服务器那么你的代码应该是这样的:

private static WebClient client = new WebClient();
private static NameValueCollection nvc= new NameValueCollection();

nvc.Add(POST_ACTION, ACTION_CODE_LOGIN);
nvc.Add(POST_EMAIL, email);
nvc.Add(POST_PASSWORD, password);

sResponse = System.Text.Encoding.ASCII.GetString(client.UploadValues(BASE_URL + ACTION_PAGE, nvc));

只要您的BASE_URL 使用https://,那么所有数据(进出服务器)都将被加密。

除了使用 https:// 作为方案之外,从客户端到服务器使用 SSL/TLS 的 IOW 不需要客户端做任何特殊的事情(使用证书),因为操作系统提供保护数据传输所需的一切(例如可信根)。

关于c# - 使用带有 HTTPS 证书的 System.Net.WebClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7402752/

相关文章:

java - 从基于 Glassfish 的 Web-AP 访问 HTTPS Web 服务

c - SSL:ERROR:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:644:Expecting: CERTIFICATE

带有 pfx 证书的 Java 打开 HttpsUrlConnection

c# - 使用 Httpwebrequest 发送文件

cocoa-touch - 如何在IOS中进行基本的http

C# 网络打印

c# - .gif 在整个循环结束之前不会动画?

c# - ASP.NET 数据集 getdataBy 无法启用约束。一行或多行包含违反非空、唯一或外键约束的值

xml - 创建按站点许可证(算法)

c# - 使用另一个线程在 WPF 中创建新窗口时的奇怪行为