问题描述
我想创建自己的自定义HTTP请求。 WebClient类是非常酷,但它会自动创建HTTP请求。我想我需要创建一个网络连接到Web服务器,并通过该流通过我的数据,但我不熟悉,将支持这种事情的库类。
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 connection to the web server and pass my data over that stream, but I'm unfamiliar with the library classes that would support that kind of thing.
(背景下,我工作的一些$ C $下,我要教一个网络编程类。我希望我的学生了解发生了什么内部HTTP的黑盒子的基础知识。)
(Context, I'm working on some code for a web programming class that I'm teaching. I want my students to understand the basics of what's happening inside the "black box" of HTTP.)
推荐答案
要真正理解HTTP协议的,你可以使用内部的类:
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());
}
}
另一种可能性是激活跟踪通过把下面的内容的app.config
键,只需使用 Web客户端以执行一个HTTP请求:
Another possibility is to activate tracing by putting the following into your app.config
and just use WebClient to perform an HTTP request:
<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调用:
Then you can perform an HTTP call:
using (var client = new WebClient())
{
var result = client.DownloadString("http://www.google.com");
}
最后分析了产生的 network.log
文件中的网络流量。 Web客户端
也将遵循HTTP重定向。
And finally analyze the network traffic in the generated network.log
file. WebClient
will also follow HTTP redirects.
这篇关于在.net中如何创建一个HTTP请求手动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!