如何连接HTTPS代理
本文关键字:HTTPS 代理 连接 何连接 | 更新日期: 2023-09-27 18:04:42
我试图通过使用套接字的代理连接到HTTPS服务器。据我所知,当使用HTTP代理时,应该将套接字连接到它,然后与它交互,因为它是真正的服务器。对于HTTP,这种方法可以工作,但是对于HTTPS则不行。为什么?
这是一个连接到HTTPS服务器的简单程序using System;
using System.Text;
using System.Net.Sockets;
using System.Net.Security;
namespace SslTcpClient
{
public class SslTcpClient
{
public static void Main(string[] args)
{
string host = "encrypted.google.com";
string proxy = "127.0.0.1";//host;
int proxyPort = 8888;//443;
// Connect socket
TcpClient client = new TcpClient(proxy, proxyPort);
// Wrap in SSL stream
SslStream sslStream = new SslStream(client.GetStream());
sslStream.AuthenticateAsClient(host);
// Send request
byte[] request = Encoding.UTF8.GetBytes(String.Format("GET https://{0}/ HTTP/1.1'r'nHost: {0}'r'n'r'n", host));
sslStream.Write(request);
sslStream.Flush();
// Read response
byte[] buffer = new byte[2048];
int bytes;
do
{
bytes = sslStream.Read(buffer, 0, buffer.Length);
Console.Write(Encoding.UTF8.GetString(buffer, 0, bytes));
} while (bytes != 0);
client.Close();
Console.ReadKey();
}
}
}
当proxy = host
和proxyPort = 443
连接成功。但是当我将它们设置为127.0.0.1:8888(本地主机上的fiddler代理)时,它不起作用。程序挂在sslStream.AuthenticateAsClient(host);
为什么?Fiddler支持HTTPS(浏览器可以通过它连接)。
注:不,我不能在我的情况下使用HttpWebRequest
我自己解决了。下面是解决方案:
using System;
using System.Text;
using System.Net.Sockets;
using System.Net.Security;
namespace SslTcpClient
{
public class SslTcpClient
{
public static void Main(string[] args)
{
string host = "encrypted.google.com";
string proxy = "127.0.0.1";//host;
int proxyPort = 8888;//443;
byte[] buffer = new byte[2048];
int bytes;
// Connect socket
TcpClient client = new TcpClient(proxy, proxyPort);
NetworkStream stream = client.GetStream();
// Establish Tcp tunnel
byte[] tunnelRequest = Encoding.UTF8.GetBytes(String.Format("CONNECT {0}:443 HTTP/1.1'r'nHost: {0}'r'n'r'n", host));
stream.Write(tunnelRequest , 0, tunnelRequest.Length);
stream.Flush();
// Read response to CONNECT request
// There should be loop that reads multiple packets
bytes = stream.Read(buffer, 0, buffer.Length);
Console.Write(Encoding.UTF8.GetString(buffer, 0, bytes));
// Wrap in SSL stream
SslStream sslStream = new SslStream(stream);
sslStream.AuthenticateAsClient(host);
// Send request
byte[] request = Encoding.UTF8.GetBytes(String.Format("GET https://{0}/ HTTP/1.1'r'nHost: {0}'r'n'r'n", host));
sslStream.Write(request, 0, request.Length);
sslStream.Flush();
// Read response
do
{
bytes = sslStream.Read(buffer, 0, buffer.Length);
Console.Write(Encoding.UTF8.GetString(buffer, 0, bytes));
} while (bytes != 0);
client.Close();
Console.ReadKey();
}
}
}