本文介绍了有Web客户端和HttpWebRequest的类.NET之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在那里的 Web客户端的HttpWebRequest 类.NET之间有什么区别?他们都做的非常类似的事情。事实上,为什么没有他们合并成一个类(太多的方法/变量等可能是原因之一,但还有其他类的.NET打破这个规则)。

What difference is there between the WebClient and the HttpWebRequest classes in .NET? They both do very similar things. In fact, why weren't they merged into one class (too many methods/variables etc may be one reason but there are other classes in .NET which breaks that rule).

感谢。

推荐答案

Web客户端是建立在HttpWebRequest的顶部,以简化最常见的任务更高级的抽象。举例来说,如果你想获得的内容出一个HttpWebResponse,你必须从响应流中读取:

WebClient is a higher-level abstraction built on top of HttpWebRequest to simplify the most common tasks. For instance, if you want to get the content out of an HttpWebResponse, you have to read from the response stream:

var http = (HttpWebRequest)WebRequest.Create("http://example.com");
var response = http.GetResponse();

var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();

使用Web客户端,你只是做 DownloadString

With WebClient, you just do DownloadString:

var client = new WebClient();
var content = client.DownloadString("http://example.com");

注:我离开了从两个例子简洁的使用语句。你一定要小心处置您的网络请求对象正确。

Note: I left out the using statements from both examples for brevity. You should definitely take care to dispose your web request objects properly.

在一般情况下,Web客户端有利于快速和肮脏的简单请求和HttpWebRequest的好,当你需要更好地控制整个要求。

In general, WebClient is good for quick and dirty simple requests and HttpWebRequest is good for when you need more control over the entire request.

这篇关于有Web客户端和HttpWebRequest的类.NET之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 11:24