如何在.Net中手动创建HTTP请求?

Jef*_*eff 6 .net webclient http

我想创建自己的自定义HTTP请求.WebClient类非常酷,但它会自动创建HTTP请求.我想我需要创建一个到Web服务器的网络连接,并通过该流传递我的数据,但我不熟悉支持这种事情的库类.

(上下文,我正在为我正在教授的Web编程课程编写一些代码.我希望我的学生能够理解HTTP"黑盒子"中发生的事情的基础知识.)

Dar*_*rov 18

要真正了解HTTP协议的内部,您可以使用TcpClient类:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

另一种可能性是通过将以下内容放入您的方法来激活跟踪,app.config并使用WebClient来执行HTTP请求:

<configuration>
  <system.diagnostics>
    <sources>
      <source name="System.Net" tracemode="protocolonly">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>
    </sources>
    <switches>
      <add name="System.Net" value="Verbose"/>
    </switches>
    <sharedListeners>
      <add name="System.Net"
           type="System.Diagnostics.TextWriterTraceListener"
           initializeData="network.log" />
    </sharedListeners>
    <trace autoflush="true"/>
  </system.diagnostics>
</configuration>
Run Code Online (Sandbox Code Playgroud)

然后你可以执行HTTP调用:

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

最后分析生成的network.log文件中的网络流量.WebClient也将遵循HTTP重定向.