HttpRequest,WebRequest,HttpWebRequest,WebClient,HttpClient 之间的区别

时间:2023-12-17 20:42:50

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。