通过C#连接HTTP方法

时间:2011-11-01 12:14:39

标签: c# http sockets

早上好 我是C#程序员,我遇到了问题

我试图打开socket以获取HTTP连接并将该页面作为字节流读取 一切都是对的, 例如,通过C#Socket获取谷歌的主页, 我遵循的步骤是:

1.打开流并连接到谷歌服务器:

Socket skt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
skt.Connect("www.google.com", 80);

2.准备请求并将其放在字节数组中:

string hdrs = "GET / HTTP/1.1\r\n"
    + "Host: www.google.com\r\n\r\n";
byte[] req_as_bytes = Encoding.UTF8.GetBytes(hdrs);

3.发送HTTP请求:

skt.Send(req_as_bytes);

4.收到回复:

byte[] data = new byte[1024 * 200]; // 200 kilo bytes
int t = skt.Receive(data);
Console.WriteLine(Encoding.UTF8.GetString(data,0,t));

但是当我将http方法从[GET]更改为[CONNECT]时, 反应将是空的!或者没有从服务器收到任何数据 新请求是:

string hdrs = "CONNECT www.google.com:443 HTTP/1.1\r\n"
    + "Host: www.google.com:443\r\n"
    + "Proxy-Connection: keep-alive\r\n\r\n";

任何人都可以帮助我吗?

完整代码:

static void Main(string[] args)
{
    Socket skt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    skt.Connect("www.google.com", 443);
    string hdrs = "CONNECT www.google.com:443 HTTP/1.1\r\n"
        + "Host: www.google.com:443\r\n"
        + "Proxy-Connection: keep-alive\r\n\r\n";
    byte[] req_as_bytes = Encoding.UTF8.GetBytes(hdrs);
    skt.Send(req_as_bytes);
    byte[] data = new byte[1024 * 200]; // 200 kilo bytes
    int t = skt.Receive(data);
    Trace.WriteLine(Encoding.UTF8.GetString(data, 0, t);
    skt.Shutdown(SocketShutdown.Both);
    skt.Close();
}
谢谢...... Mhamad

2 个答案:

答案 0 :(得分:2)

如果您确实想要实施HTTPS服务器,则需要阅读RFC

BTW,它已经在.NET中实现:System.Net.HttpListener

答案 1 :(得分:0)

socket.Connect("www.google.com", **80**);

string hdrs = "CONNECT www.google.com:**443** HTTP/1.1\r\n"
    + "Host: www.google.com:443\r\n"
    + "Proxy-Connection: keep-alive\r\n\r\n";

80 - 443冲突!

如果您使用443端口?必须使用.NET 4.0 FRAMEWORK- SSLSTREAM类..