我想用套接字发送GET / POST请求,我有这个代码:
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(Url, 80);
byte[] contentLenght = Encoding.ASCII.GetBytes(Data);
string[] masRequestString ={
"GET /"+Data+" HTTP/1.1\r\n" ,
"Host: "+Url+"\r\n",
"User-Agent: "+textBox1.Text+"\r\n",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n",
"Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n",
"Referer: "+textBox2.Text+"\r\n"};
string request = string.Concat(masRequestString);
Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
socket.Send(bytesSent, bytesSent.Length, 0);
Byte[] bytesReceived = new Byte[0x400];
int bytes = socket.Receive(bytesReceived, bytesReceived.Length, 0);
string content = Encoding.ASCII.GetString(bytesReceived, 0, bytes);
当我尝试发送请求时,嗅探器不会看到它。为什么呢?
答案 0 :(得分:4)
我不知道你怎么做嗅闻但是
\r\n
。content-length
标头和分块编码。Content-type
标头之外没有任何意义,因为在GET请求中不会发送任何内容(仅在响应中)。我建议您在尝试实施HTTP之前先了解一下HTTP的工作原理。当然,使用已经存在的实现会好得多,因为在短暂的外观之后,HTTP似乎不是简单的协议。
答案 1 :(得分:0)
不要自己尝试实现HTTP,socket可以获取数据并将其包装起来。 使用HTTP库:
using System.Net;
string url = "https://www.example.com/scriptname.php?var1=hello";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();