我想创建我自己的自定义HTTP请求。WebClient类非常酷,但它会自动创建HTTP请求。我想我需要创建一个到web服务器的网络连接,并通过该流传递我的数据,但我不熟悉支持这类东西的库类。
(上下文,我正在为我正在教授的web编程课程编写一些代码。我希望我的学生理解HTTP“黑盒”中发生的事情的基础知识。)
发布于 2010-01-21 22:01:39
要真正理解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());
}
}另一种可能是通过将以下内容放入您的app.config中来执行activate tracing,然后使用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>然后,您可以执行HTTP调用:
using (var client = new WebClient())
{
var result = client.DownloadString("http://www.google.com");
}最后分析生成的network.log文件中的网络流量。WebClient还将遵循HTTP重定向。
发布于 2010-01-21 22:00:34
根据需要使用WebRequest或WebResponse类。
如果您需要比它们提供的更低的级别,请查看其他System.Net.Sockets.*客户机类,如TcpClient。
发布于 2010-01-21 22:01:01
如果您想编写自己的低级客户端,请查看System.Net.Sockets.TcpClient。但是,对于HTTP GET和POST,您可以使用HttpWebRequest和HttpWebResponse类。
如果你真的很自虐,你可以比TcpClient低一点,实现你自己的Socket,参见Socket class。
https://stackoverflow.com/questions/2109695
复制相似问题