RanRag RanRag - 2 months ago 17
C# Question

C#: How to execute a HTTP request using sockets?

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("\r\n"));

bytes = sock.Receive(bytesReceived, bytesReceived.Length, 0);
page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
Console.WriteLine(page);
sock.Close();
}
}


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


The response I get from my code is
SNP/3.0/107/BadPacket
.

So, what is wrong with my code.

Snarl Request format specification

Answer

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\r\n" + 
    "Host: 127.0.0.1\r\n" +
    "Content-Length: 0\r\n" +
    "\r\n";

The HTTP 1.1 specification can be found here: http://www.w3.org/Protocols/rfc2616/rfc2616.html