在网上搜寻了半天没有查到C# socket发送http请求(java的倒是有一篇也很含蓄),于是自己根据http协议规范写了个C#的http socket请求。
class Program
static void Main(string[] args)
byte[] data = new byte[1024];
string input, stringData;
IPHostEntry gist = Dns.GetHostByName("www.baidu.com");
IPAddress ip =
gist.AddressList[0];
//得到IP
IPEndPoint ipEnd = new IPEndPoint(ip, 80);//默认80端口号
Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);//使用tcp协议
stream类型
try
socket.Connect(ipEnd);
catch (SocketException e)
Console.Write("Fail to connect server");
Console.Write(e.ToString());
return;
string path = "/index.php";//这里请求的相对地址,如果访问直接www.baidu.com则不需要为空.
StringBuilder buf = new StringBuilder();
buf.Append("GET ").Append(path).Append(" HTTP/1.0\r\n");
buf.Append("Content-Type:
application/x-www-form-urlencoded\r\n");
buf.Append("\r\n");
byte[] ms =
System.Text.UTF8Encoding.UTF8.GetBytes(buf.ToString());
socket.Send(ms);
int recv = -1;
do
recv = socket.Receive(data);
stringData = Encoding.UTF8.GetString(data, 0,
recv);//如果请求的页面meta中指定了页面的encoding为gb2312则需要使用对应的Encoding来对字节进行转换
Console.Write(stringData);
} while (recv != -1);
Console.Write("disconnect from server");
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
}