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. Storm知识点

    1. 离线计算是什么? 离线计算:批量获取数据.批量传输数据.周期性批量计算数据.数据展示 代表技术:Sqoop批量导入数据.HDFS批量存储数据.MapReduce批量计算数据.Hive批量计算数据 ...

  2. postman简介及基本用法

    从分层测试角度来说,接口测试是相对来说性价比最高的,且作为功能测试进阶的必备技能,接口测试值得大家都去学习掌握. 工欲善其事,必先利其器,好的工具能更好的帮助工程师更高效率的完成工作. 常见的接口测试 ...

  3. face detection[PyramidBox]

    本文来自<PyramidBox: A Context-assisted Single Shot Face Detector>,是来自百度的作品,时间线为2018年8月. 0 引言 最近基于 ...

  4. Android开发常用权限设置

    加在AndroidManifest.xml 文件中manifest标签以内,application以外 例如:<!--网络权限 --> <uses-permission androi ...

  5. Day3 Python基础之while、for循环(二)

    1.数据运算 算数运算 整除运算:// 取余运算:% 指数运算:** 赋值运算 b+=a;等价于b=b+a 比较运算 >,<,==,!=,>=,<= 逻辑运算符 and .or ...

  6. Spring Boot 中使用 @Transactional 注解配置事务管理

    事务管理是应用系统开发中必不可少的一部分.Spring 为事务管理提供了丰富的功能支持.Spring 事务管理分为编程式和声明式的两种方式.编程式事务指的是通过编码方式实现事务:声明式事务基于 AOP ...

  7. Golang 字符串操作--使用strings、strconv包

    strings包 package main import ( "fmt" "strings" ) func main() { //func Count(s, s ...

  8. shell脚本--初识CGI

    CGI按照百度百科的定义,如下: CGI 是Web 服务器运行时外部程序的规范,按CGI 编写的程序可以扩展服务器功能.CGI 应用程序能与浏览器进行交互,还可通过数据库API 与数据库服务器等外部数 ...

  9. composer 自动加载 通过classmap自动架子啊

    https://github.com/brady-wang/composer github地址 composer加载自己写的类 放入一个目录下 更改composer.json "autolo ...

  10. redis4.X

    tar -zxvf ****cd /redismakecd /srcmake install vi redis.confdaemonize yes mkdir /usr/local/redis/bin ...