HttpRequest,WebRequest,HttpWebRequest,WebClient,HttpClient 之間的區別

HttpRequest,WebRequest,HttpWebRequest,WebClient,HttpClient 今天咱們來聊一下他們之間的關係與區別。html

 

HttpRequest 類

.NET Framework 2.0

使 ASP.NET 可以讀取客戶端在 Web 請求期間發送的 HTTP 值。web

命名空間: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 > 1000)
            {
                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=0; 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 類。windows

命名空間:   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 資源。app

由於 WebRequest 類是 abstract 類的實際行爲 WebRequest 實例在運行時由子代類返回 Create 方法。 默認值和異常有關的詳細信息,請參閱文檔對於子代類中,如 HttpWebRequest 和 FileWebRequest。less

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 特定的實現。async

命名空間:   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 == 0)
        {
            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[0]);
        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。

相關文章
相關標籤/搜索