作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试使用套接字通过代理连接到 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();
}
}
}
关于c# - 如何连接到 HTTPS 代理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6940893/
我正在开发一个 voip 调用应用程序。我需要做的是在接到来电时将 Activity 带到前台。我在应用程序中使用 Twilio,并在收到推送消息时开始调用。 问题是我试图在接到任何电话时显示 Act
我是一名优秀的程序员,十分优秀!