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

Viewed 37226

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

4 Answers

The minimum requirement for a HTTP request is "GET / HTTP/1.0\r\n\r\n" (if removing the Host is allowed). But in SNARL, you must input the content-length (what I most heard).

So,

        Socket sck = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);

        sck.Connect(ip, port);
        sck.Send(Encoding.UTF8.GetBytes("THE HTTP REQUEST HEADER"));
        Console.WriteLine("SENT");
        string message = null;
        byte[] bytesStored = new byte[sck.ReceiveBufferSize];
        int k1 = sck.Receive(bytesStored);
        for (int i = 0; i < k1; i++)
        {
            message = message + Convert.ToChar(bytesStored[i]).ToString();
        }
        Console.WriteLine(message); // PRINT THE RESPONSE

I tested on several sites and it works perfectly. If it didn't work, then you should fix it by adding more header (most likely solution).

Related