HttpRequest,WebRequest,HttpWebRequest,WebClient,HttpClient 今天我们来聊一下他们之间的关系与区别。

HttpRequest 类

.NET Framework 2.0

使 ASP.NET 能够读取客户端在 Web 请求期间发送的 HTTP 值。

命名空间:System.Web
程序集:System.Web(在 system.web.dll 中)

继承层次结构
System.Object 
  System.Web.HttpRequest
就是当时我们常用的request
<%@ Page Language="C#" %>
<%@ import Namespace="System.Threading" %>
<%@ import Namespace="System.IO" %>
<script runat="server"> /* NOTE: To use this sample, create a c:\temp\CS folder,
* add the ASP.NET account (in IIS 5.x <machinename>\ASPNET,
* in IIS 6.x NETWORK SERVICE), and give it write permissions
* to the folder.*/ private const string INFO_DIR = @"c:\temp\CS\RequestDetails";
public static int requestCount; private void Page_Load(object sender, System.EventArgs e)
{ // Create a variable to use when iterating
// through the UserLanguages property.
int langCount; int requestNumber = Interlocked.Increment(ref requestCount); // Create the file to contain information about the request.
string strFilePath = INFO_DIR + requestNumber.ToString() + @".txt"; StreamWriter sw = File.CreateText(strFilePath); try
{
// Write request information to the file with HTML encoding.
sw.WriteLine(Server.HtmlEncode(DateTime.Now.ToString()));
sw.WriteLine(Server.HtmlEncode(Request.CurrentExecutionFilePath));
sw.WriteLine(Server.HtmlEncode(Request.ApplicationPath));
sw.WriteLine(Server.HtmlEncode(Request.FilePath));
sw.WriteLine(Server.HtmlEncode(Request.Path)); // Iterate through the Form collection and write
// the values to the file with HTML encoding.
// String[] formArray = Request.Form.AllKeys;
foreach (string s in Request.Form)
{
sw.WriteLine("Form: " + Server.HtmlEncode(s));
} // Write the PathInfo property value
// or a string if it is empty.
if (Request.PathInfo == String.Empty)
{
sw.WriteLine("The PathInfo property contains no information.");
}
else
{
sw.WriteLine(Server.HtmlEncode(Request.PathInfo));
} // Write request information to the file with HTML encoding.
sw.WriteLine(Server.HtmlEncode(Request.PhysicalApplicationPath));
sw.WriteLine(Server.HtmlEncode(Request.PhysicalPath));
sw.WriteLine(Server.HtmlEncode(Request.RawUrl)); // Write a message to the file dependent upon
// the value of the TotalBytes property.
if (Request.TotalBytes > )
{
sw.WriteLine("The request is 1KB or greater");
}
else
{
sw.WriteLine("The request is less than 1KB");
} // Write request information to the file with HTML encoding.
sw.WriteLine(Server.HtmlEncode(Request.RequestType));
sw.WriteLine(Server.HtmlEncode(Request.UserHostAddress));
sw.WriteLine(Server.HtmlEncode(Request.UserHostName));
sw.WriteLine(Server.HtmlEncode(Request.HttpMethod)); // Iterate through the UserLanguages collection and
// write its HTML encoded values to the file.
for (langCount=; langCount < Request.UserLanguages.Length; langCount++)
{
sw.WriteLine(@"User Language " + langCount +": " + Server.HtmlEncode(Request.UserLanguages[langCount]));
}
} finally
{
// Close the stream to the file.
sw.Close();
} lblInfoSent.Text = "Information about this request has been sent to a file.";
} private void btnSendInfo_Click(object sender, System.EventArgs e)
{
lblInfoSent.Text = "Hello, " + Server.HtmlEncode(txtBoxName.Text) +
". You have created a new request info file.";
} </script>
<html>
<head>
</head>
<body>
<form runat="server">
<p>
</p>
<p>
Enter your hame here:
<asp:TextBox id="txtBoxName" runat="server"></asp:TextBox>
</p>
<p>
<asp:Button id="btnSendInfo" onclick="btnSendInfo_Click" runat="server" Text="Click Here"></asp:Button>
</p>
<p>
<asp:Label id="lblInfoSent" runat="server"></asp:Label>
</p>
</form>
</body>
</html>

WebRequest 类

.NET Framework (current version)

对统一资源标识符 (URI) 发出请求。 这是一个 abstract 类。

命名空间:   System.Net
程序集:  System(位于 System.dll)

System.Object
  System.MarshalByRefObject
    System.Net.WebRequest
      System.IO.Packaging.PackWebRequest
      System.Net.FileWebRequest
      System.Net.FtpWebRequest
      System.Net.HttpWebRequest

WebRequest 是 abstract 基类,用于从 Internet 中访问数据的.NET Framework 的请求/响应模型。 使用请求/响应模型的应用程序可以在应用程序的实例的工作一种协议不可知的方式从 Internet 请求数据 WebRequest 类时特定于协议的子代类执行请求的详细信息。

从特定的 URI,例如 Web 页的服务器上的应用程序发送请求。 URI 用于确定要从列表中创建的正确子代类 WebRequest 后代注册应用程序。WebRequest 后代通常被注册来处理特定的协议,如 HTTP 或 FTP,但也可以注册来处理对特定服务器或服务器上的路径的请求。

WebRequest 类将引发 WebException 中发生错误时访问 Internet 资源时。 Status 属性是一个 WebExceptionStatus 值,该值指示错误的来源。 当 Status 是 WebExceptionStatus.ProtocolError, 、 Response 属性包含 WebResponse 收到来自 Internet 资源。

因为 WebRequest 类是 abstract 类的实际行为 WebRequest 实例在运行时由子代类返回 Create 方法。 默认值和异常有关的详细信息,请参阅文档对于子代类中,如 HttpWebRequest 和 FileWebRequest。

using System;
using System.IO;
using System.Net;
using System.Text; namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main ()
{
// Create a request for the URL.
WebRequest request = WebRequest.Create ("http://www.contoso.com/default.html");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
// Display the status.
Console.WriteLine (response.StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Cleanup the streams and the response.
reader.Close ();
dataStream.Close ();
response.Close ();
}
}
}

HttpWebRequest 类

.NET Framework (current version)
 

发布日期: 2016年7月

提供 WebRequest 类的 HTTP 特定的实现。

命名空间:   System.Net
程序集:  System(位于 System.dll)

System.Object
  System.MarshalByRefObject
    System.Net.WebRequest
      System.Net.HttpWebRequest
HttpWebRequest myReq =
(HttpWebRequest)WebRequest.Create("http://www.contoso.com/");

WebClient 类

.NET Framework (current version)
 

提供用于将数据发送到和接收来自通过 URI 确认的资源数据的常用方法。

命名空间:   System.Net
程序集:  System(位于 System.dll)

System.Object
  System.MarshalByRefObject
    System.ComponentModel.Component
      System.Net.WebClient
using System;
using System.Net;
using System.IO; public class Test
{
public static void Main (string[] args)
{
if (args == null || args.Length == )
{
throw new ApplicationException ("Specify the URI of the resource to retrieve.");
}
WebClient client = new WebClient (); // Add a user agent header in case the
// requested URI contains a query. client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); Stream data = client.OpenRead (args[]);
StreamReader reader = new StreamReader (data);
string s = reader.ReadToEnd ();
Console.WriteLine (s);
data.Close ();
reader.Close ();
}
}

HttpClient 类

Provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.

System.Object 
  System.Net.Http.HttpMessageInvoker
    System.Net.Http.HttpClient
 

命名空间:  System.Net.Http
程序集:  System.Net.Http(在 System.Net.Http.dll 中)

重要的 API

  • HttpClient
  • Windows.Web.Http
  • Windows.Web.Http.HttpResponseMessage

依据 HTTP 2.0 和 HTTP 1.1 协议,使用 HttpClient 和其余的 Windows.Web.Http 命名空间 API 发送和接收信息。

HttpClient 和 Windows.Web.Http 命名空间概述

Windows.Web.Http 命名空间及相关 Windows.Web.Http.Headers 和 Windows.Web.Http.Filters 命名空间中的类为充当 HTTP 客户端的通用 Windows 平台 (UWP) 应用提供了一个编程接口,以便于执行基本 GET 请求或实现下面列出的更高级的 HTTP 功能。

  • 执行常见操作(DELETE、GET、PUT 和 POST)的方法。 上述每种请求都作为异步操作进行发送。

  • 支持常见的身份验证设置和模式。

  • 访问有关传输的安全套接字层 (SSL) 详细信息。

  • 高级应用随附自定义筛选器的功能。

  • 获取、设置和删除 Cookie 的功能。

  • 异步方法上提供的 HTTP 请求进度信息。

Windows.Web.Http.HttpRequestMessage 类用于声明由 Windows.Web.Http.HttpClient 发送的 HTTP 请求消息。 Windows.Web.Http.HttpResponseMessage 类用于声明从 HTTP 请求接收到的 HTTP 响应消息。 HTTP 消息由 IETF 在 RFC 2616 中进行定义。

Windows.Web.Http 命名空间用于声明 HTTP 内容作为 HTTP 实体正文和包含 Cookie 的标头。 HTTP 内容可以与 HTTP 请求或 HTTP 响应相关联。 Windows.Web.Http 命名空间提供很多不同的类来声明 HTTP 内容。

  • HttpBufferContent。 缓冲区形式的内容
  • HttpFormUrlEncodedContent。 使用 application/x-www-form-urlencoded MIME 类型编码的名称和值元组形式的内容
  • HttpMultipartContent。 采用 multipart/\* MIME 类型格式的内容。
  • HttpMultipartFormDataContent。 编码为 multipart/form-data MIME 类型的内容。
  • HttpStreamContent。 流(供 HTTP GET 方法接收数据和 HTTP POST 方法上载数据使用的内部类型)形式的内容
  • HttpStringContent。 字符串形式的内容。
  • IHttpContent - 供开发人员创建其自己的内容对象的基本界面

“通过 HTTP 发送简单的 GET 请求”部分中的代码段使用 HttpStringContent 类,以字符串的形式表示来自 HTTP GET 请求的 HTTP 响应。

Windows.Web.Http.Headers 命名空间支持创建 HTTP 标头和 Cookie,然后再将生成的 HTTP 标头和 Cookie 作为属性与 HttpRequestMessage 和 HttpResponseMessage 对象相关联。

通过 HTTP 发送简单的 GET 请求

正如本文前面提到的,Windows.Web.Http 命名空间允许 UWP 应用发送 GET 请求。 以下代码段演示了如何使用 Windows.Web.Http.HttpClient 和 Windows.Web.Http.HttpResponseMessage 类读取来自 GET 请求的响应,来将 GET 请求发送到 http://www.contoso.com。

/Create an HTTP client object
Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); //Add a user-agent header to the GET request.
var headers = httpClient.DefaultRequestHeaders; //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true,
//especially if the header value is coming from user input.
string header = "ie";
if (!headers.UserAgent.TryParseAdd(header))
{
throw new Exception("Invalid header value: " + header);
} header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
if (!headers.UserAgent.TryParseAdd(header))
{
throw new Exception("Invalid header value: " + header);
} Uri requestUri = new Uri("http://www.contoso.com"); //Send the GET request asynchronously and retrieve the response as a string.
Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
string httpResponseBody = ""; try
{
//Send the GET request
httpResponse = await httpClient.GetAsync(requestUri);
httpResponse.EnsureSuccessStatusCode();
httpResponseBody = await httpResponse.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
}

Windows.Web.Http 中的异常

将统一资源标识符 (URI) 的无效字符串传递给 Windows.Foundation.Uri 对象的构造函数时,将引发异常。

.NET:Windows.Foundation.Uri 类型在 C# 和 VB 中显示为 System.Uri。

在 C# 和 Visual Basic 中,通过使用 .NET 4.5 中的 System.Uri 类和 System.Uri.TryCreate 方法之一在构造 URI 之前测试从用户收到的字符串,可以避免该错误。

在 C++ 中,没有可用于试用字符串和将其解析到 URI 的方法。 如果应用获取 Windows.Foundation.Uri 用户输入,则构造函数应位于 try/catch 块中。 如果引发了异常,该应用可以通知用户并请求新的主机名。

Windows.Web.Http 缺少方便函数。 所以,使用 HttpClient 和该命名空间中其他类的应用需要使用 HRESULT 值。

在采用 C#、VB.NET 编写的使用 .NET Framework 4.5 的应用中发生异常时,System.Exception 表示应用执行期间的错误。 System.Exception.HResult 属性将返回分配到特定异常的 HRESULT。 System.Exception.Message 属性将返回用于描述异常的消息。 可能的 HRESULT 值将在 Winerror.h 头文件中列出。 应用可以筛选特定 HRESULT 值来根据异常原因修改应用行为。

在使用托管的 C++ 的应用中发生异常时,Platform::Exception 表示应用执行期间的错误。 Platform::Exception::HResult 属性将返回分配到特定异常的 HRESULT。 Platform::Exception::Message 属性将返回系统提供的与 HRESULT 值关联的字符串。 可能的 HRESULT 值将在 Winerror.h 头文件中列出。 应用可以筛选特定 HRESULT 值来基于异常原因修改应用行为。

对于大多数参数验证错误,返回的 HRESULT 为 E_INVALIDARG。 对于某些非法的方法调用,返回的 HRESULT 为 E_ILLEGAL_METHOD_CALL。

HttpRequest,WebRequest,HttpWebRequest,WebClient,HttpClient 之间的区别的更多相关文章

  1. webrequest HttpWebRequest webclient/HttpClient

    webrequest(abstract类,不可直接用) <--- (继承)---- HttpWebRequest(更好的控制请求) <--- (继承)---- webclient (简单快 ...

  2. .net学习笔记----HttpRequest,WebRequest,HttpWebRequest区别

    WebRequest是一个虚类/基类,HttpWebRequest是WebRequest的具体实现 HttpRequest类的对象用于服务器端,获取客户端传来的请求的信息,包括HTTP报文传送过来的所 ...

  3. WebClient, HttpClient, HttpWebRequest ,RestSharp之间的区别与抉择

    NETCore提供了三种不同类型用于生产的REST API: HttpWebRequest;WebClient;HttpClient,开源社区创建了另一个名为RestSharp的库.如此多的http库 ...

  4. .Net5下WebRequest、WebClient、HttpClient是否还存在使用争议?

    WebRequest.WebClient.HttpClient 是C#中常用的三个Http请求的类,时不时也会有人发表对这三个类使用场景的总结,本人是HttpClient 一把梭,也没太关注它们的内部 ...

  5. HttpRequest 和HttpWebRequest的区别

    [1]问题: asp.NET C#  中HttpRequest 和HttpWebRequest的区别 HttpRequest 与HttpWebRequest 有什么区别? 网上中文的帖子很多,但是答案 ...

  6. struts2中拦截器与过滤器之间的区别

    首先是一张经典的struts2原理图 当接收到一个httprequest , a) 当外部的httpservletrequest到来时 b) 初始到了servlet容器 传递给一个标准的过滤器链 c) ...

  7. servlet,RMI,webservice之间的区别

    最近项目中有提供或者调用别的接口,在纠结中到底是用servlet还是用webservice,所以上网查看了下他们以及RMI之间的区别,方便加深了解. 首先比较下servlet和webservice下  ...

  8. select、poll、epoll之间的区别总结

    select.poll.epoll之间的区别总结 05/05. 2014 select,poll,epoll都是IO多路复用的机制.I/O多路复用就通过一种机制,可以监视多个描述符,一旦某个描述符就绪 ...

  9. 你真的会玩SQL吗?EXISTS和IN之间的区别

    你真的会玩SQL吗?系列目录 你真的会玩SQL吗?之逻辑查询处理阶段 你真的会玩SQL吗?和平大使 内连接.外连接 你真的会玩SQL吗?三范式.数据完整性 你真的会玩SQL吗?查询指定节点及其所有父节 ...

随机推荐

  1. 关于NOIP2018复赛若干巧合的声明

    关于NOIP2018复赛若干巧合的声明 导言 参加NOIP2018时本人学龄只有两个月,却斩获了省一等奖,保送了重点中学的重点班,这看上去是个我创造的神话,然而,在我自己心中,我认为这只是个巧合(其实 ...

  2. 蓝牙BLE设备主机重启回连流程分析

    如果一个BLE设备已经与蓝牙中心设备连接上,那么当中心设备的断电重启,其依然会和配对过的BLE设备连接上,而不需要重新走配对的流程,这个过程叫做回连. 这篇文章就分析一下当中心设备断电重启之后,其与B ...

  3. 蓝牙SDP协议概述

    之前写了一篇 bluedroid对于sdp的实现的源码分析   ,他其实对于sdp 协议本身的分析并不多,而是侧重于 sdp 处于Android bluedroid 架构中的代码流程,这篇文章,是针对 ...

  4. 【原创】研发应该懂的binlog知识(下)

    引言 这篇是<研发应该懂的binlog知识(上)>的下半部分.在本文,我会阐述一下binlog的结构,以及如何使用java来解析binlog. 不过,话说回来,其实严格意义上来说,研发应该 ...

  5. Git 使用vi或vim命令打开、关闭、保存文件

    1 vi & vim 有两种工作模式: (1)命令模式:接受.执行 vi & vim 操作命令的模式,打开文件后的默认模式: (2)编辑模式:对打开的文件内容进行 增.删.改 操作模式 ...

  6. HDU - 4027 线段树减枝

    这题太坑了...满满的都是坑点 1号坑点:给定左右区间有可能是反的...因为题目上说x,y之间,但是没有说明x,y的大小关系(害我一直RE到怀疑人生) 2号坑点:开根号的和不等于和开根号(还好避开了) ...

  7. HDU - 1754 线段树-单点修改+询问区间最大值

    这个也是线段树的经验问题,待修改的,动态询问区间的最大值,只需要每次更新的时候,去把利用子节点的信息进行修改即可以. 注意更新的时候区间的选择,需要对区间进行二分. #include<iostr ...

  8. 用WSDL4J解析types标签中的内容

    WSDL4J是一种用来解析WSDL文本的常用工具. 但网络上用WSDL4J来解析wsdl文档complexType标签中内容的问题一大堆也没有有效的解决方法.今天在我“遍历”wsdl4j的api文档和 ...

  9. asp.net mvc 自定义全局过滤器 验证用户是否登录

    一般具有用户模块的系统都需要对用户是否登录进行验证,如果用户登录了就可以继续操作,否则退回用户的登录页面 对于这样的需求我们可以通过自定义一个独立的方法来完成验证的操作,但是这样代码的重复率就大大提高 ...

  10. MyEclipse 配置 Tomcat

    安装好Tomcat,MyEclipse 之后,利用这两个工具可以开发部署Web 应用,步骤相对手动部署要简洁的多,这里有一个特别要注意的地方:系统里安装JDK.Tomcat.MyEclipse 的版本 ...