问题描述
我正在尝试使用套接字发出 HTTP 请求
.我的代码如下:
I am trying to make a HTTP request
using sockets. My code is as follows:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class test
{
public static void Main(String[] args)
{
string hostName = "127.0.0.1";
int hostPort = 9887;
int response = 0;
IPAddress host = IPAddress.Parse(hostName);
IPEndPoint hostep = new IPEndPoint(host, hostPort);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(hostep);
string request_url = "http://127.0.0.1/register?id=application/vnd-fullphat.test&title=My%20Test%20App";
response = sock.Send(Encoding.UTF8.GetBytes(request_url));
response = sock.Send(Encoding.UTF8.GetBytes("
"));
bytes = sock.Receive(bytesReceived, bytesReceived.Length, 0);
page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
Console.WriteLine(page);
sock.Close();
}
}
现在,当我执行上面的代码时什么也没有发生,而当我在浏览器中输入我的 request_url
时,我收到了来自 Snarl 的通知,说 Application Registered 和我得到的响应浏览器是
Now when I execute the above code nothing happens whereas when I enter my request_url
in browser I get a notification from Snarl saying that Application Registered
and the response I get from browser is
SNP/2.0/0/OK/556
我从代码中得到的响应是 SNP/3.0/107/BadPacket
.
The response I get from my code is SNP/3.0/107/BadPacket
.
那么,我的代码有什么问题.
So, what is wrong with my code.
推荐答案
必须在末尾包含 content-length 和双换行符以指示标题结束.
You must include content-length and double new line in the end to indicate end of header.
var request = "GET /register?id=application/vnd-fullphat.test&title=My%20Test%20App HTTP/1.1
" +
"Host: 127.0.0.1
" +
"Content-Length: 0
" +
"
";
可以在此处找到 HTTP 1.1 规范:http://www.w3.org/Protocols/rfc2616/rfc2616.html
The HTTP 1.1 specification can be found here: http://www.w3.org/Protocols/rfc2616/rfc2616.html
这篇关于C#:如何使用套接字执行 HTTP 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!