SoFunction
Updated on 2025-03-06

C# method of imitating http request based on socket

This article describes the method of C# using socket to simulate http requests. Share it for your reference. The specific implementation method is as follows:

using System;
using ;
using ;
using ;
using ;
using ;
using ;
class HttpHelper
{
  #region simulates client socket connection  private static Socket ConnectSocket(string server, int port)
  {
   Socket s = null;
   IPHostEntry hostEntry = null;
   // Get host related information.
   hostEntry = (server);
   // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
   // an exception that occurs when the host IP Address is not compatible with the address family
   // (typical in the IPv6 case).
   foreach (IPAddress address in )
   {
    IPEndPoint ipe = new IPEndPoint(address, port);
    Socket tempSocket =
    new Socket(, , );
    (ipe);
    if ()
    {
     s = tempSocket;
     break;
    }
    else
    {
     continue;
    }
   }
   return s;
  }
  #endregion
  The main method of #region request is the header of the http request, which can be obtained using the packet capture tool, the server can make the domain name or IP address, and the port http protocol is generally 80  public static string SocketSendReceive(string request, string server, int port)
  {
   try
   {
    Byte[] bytesSent = (request);
    Byte[] bytesReceived = new Byte[655350];
    // Create a connection    Socket s = ConnectSocket(server, port);
    if (s == null)
     return ("Connection failed");
    // Send content.    (bytesSent, , 0);
    // Receive the server home page content.
    int bytes = 0;
    string page = "Default HTML page on " + server + ":\r\n";
    //Accept the returned content.    do
    {
     bytes = (bytesReceived, , 0);
     page = page + Encoding.(bytesReceived, 0, bytes);
    }
    while (bytes > 0);
 
    return page;
   }
   catch
   {
    return ;
   }
  }
  #endregion
}

using System;
using ;
using ;
using ;
using ;
using ;
using ;
class Program
{
  public static string HeadlerInit() {
   StringBuilder sb = new StringBuilder();
   ("GET / HTTP/1.1");
   ("Host: ");
   ("Connection: keep-alive");
   ("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
   ("User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36");
   ("Accept-Encoding:deflate, sdch");
   ("Accept-Language: zh-CN,zh;q=0.8");
   ("\r\n");
   //This must be there otherwise there may be no data when received.   return ();
  }
  static void Main(string[] args)
  {
   string getStrs=HeadlerInit();
   string getHtml = (getStrs, "", 80);
   (getHtml);
  }
}

I hope this article will be helpful to everyone's C# programming.