我实质上是在尝试设置一个HTTPS客户端,该客户端可用于我正在开发的自动化测试API和其他Web服务。我对使用套接字很熟悉,但是对在代码中使用SSL / TLS却不太了解。我首先尝试设置一个客户端,该客户端使用以下标头向google.com发送HTTP请求:GET / HTTP/1.1
这个想法是通过加密连接从Google接收基本的HTTP响应。使用未加密的HTTP时,这真的很容易-我什至可以通过端口80 telnet到google中,然后输入GET / HTTP/1.1,我会收到一个不错的HTTP响应标头和HTML有效负载。实现C / C#代码以发出未加密的HTTP请求也不是很困难。SSL使我很难受。
使用下面的代码(可在https://msdn.microsoft.com/zh-cn/library/system.net.security.sslstream.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet中找到完整的示例-3),与MSDN提供的参考几乎完全相同,我可以成功连接google.com并验证服务器证书:
// Create a TCP/IP client socket.
// machineName is the host running the server application.
TcpClient client = new TcpClient(machineName, 443);
Console.WriteLine("Client connected.");
// Create an SSL stream that will close the client's stream.
SslStream sslStream = new SslStream(
client.GetStream(),
false,
new RemoteCertificateValidationCallback(ValidateServerCertificate),
null
);
// The server name must match the name on the server certificate.
try
{ …Run Code Online (Sandbox Code Playgroud)