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

前端 未结 4 666
难免孤独
难免孤独 2020-12-06 05:51

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.         


        
4条回答
  •  死守一世寂寞
    2020-12-06 06:13

    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).

提交回复
热议问题