How do I Create an HTTP Request Manually in .Net?

后端 未结 5 1824
醉话见心
醉话见心 2020-12-17 01:42

I\'d like to create my own custom HTTP requests. The WebClient class is very cool, but it creates the HTTP requests automatically. I\'m thinking I need to create a network

5条回答
  •  时光说笑
    2020-12-17 02:23

    To really understand the internals of the HTTP protocol you could use TcpClient class:

    using (var client = new TcpClient("www.google.com", 80))
    {
        using (var stream = client.GetStream())
        using (var writer = new StreamWriter(stream))
        using (var reader = new StreamReader(stream))
        {
            writer.AutoFlush = true;
            // Send request headers
            writer.WriteLine("GET / HTTP/1.1");
            writer.WriteLine("Host: www.google.com:80");
            writer.WriteLine("Connection: close");
            writer.WriteLine();
            writer.WriteLine();
    
            // Read the response from server
            Console.WriteLine(reader.ReadToEnd());
        }
    }
    

    Another possibility is to activate tracing by putting the following into your app.config and just use WebClient to perform an HTTP request:

    
      
        
          
            
              
            
          
        
        
          
        
        
          
        
        
      
    
    

    Then you can perform an HTTP call:

    using (var client = new WebClient())
    {
        var result = client.DownloadString("http://www.google.com");
    }
    

    And finally analyze the network traffic in the generated network.log file. WebClient will also follow HTTP redirects.

提交回复
热议问题