<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                # C# `HttpClient`教程 > 原文: [https://zetcode.com/csharp/httpclient/](https://zetcode.com/csharp/httpclient/) C# `HttpClient`教程展示了如何使用 C# 中的`HttpClient`創建 HTTP 請求。 在示例中,我們創建簡單的 GET 和 POST 請求。 超文本傳輸??協議(HTTP)是用于分布式,協作式超媒體信息系統的應用協議。 HTTP 是萬維網數據通信的基礎。 `HttpClient`是用于從 URI 標識的資源發送 HTTP 請求和接收 HTTP 響應的基類。 ## C# `HttpClient`狀態碼 HTTP 響應狀態代碼指示特定的 HTTP 請求是否已成功完成。 響應分為五類: * 信息響應(100–199) * 成功響應(200–299) * 重定向(300–399) * 客戶端錯誤(400–499) * 服務器錯誤(500–599) `Program.cs` ```cs using System; using System.Net.Http; using System.Threading.Tasks; namespace HttpClientStatus { class Program { static async Task Main(string[] args) { using var client = new HttpClient(); var result = await client.GetAsync("http://webcode.me"); Console.WriteLine(result.StatusCode); } } } ``` 該示例向小型網站創建 GET 請求。 我們獲得了請求的狀態碼。 ```cs using var client = new HttpClient(); ``` 創建一個新的`HttpClient`。 ```cs var result = await client.GetAsync("http://webcode.me"); ``` `GetAsync()`方法將 GET 請求作為異步操作發送到指定的 Uri。 `await`運算符會暫停對異步方法的求值,直到異步操作完成為止。 異步操作完成后,`await`操作符將返回操作結果(如果有)。 ```cs $ dotnet run OK ``` 我們得到 200 OK 狀態碼; 網站開通了。 ## C# `HttpClient` GET 請求 GET 方法請求指定資源的表示形式。 `Program.cs` ```cs using System; using System.Net.Http; using System.Threading.Tasks; namespace HttpClientEx { class Program { static async Task Main(string[] args) { using var client = new HttpClient(); var content = await client.GetStringAsync("http://webcode.me"); Console.WriteLine(content); } } } ``` 該示例向`webcode.me`網站發出 GET 請求。 它輸出主頁的簡單 HTML 代碼。 ```cs var content = await client.GetStringAsync("http://webcode.me"); ``` `GetStringAsync()`發送 GET 請求到指定的 Uri,并在異步操作中將響應主體作為字符串返回。 ```cs $ dotnet run <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My html page</title> </head> <body> <p> Today is a beautiful day. We go swimming and fishing. </p> <p> Hello there. How are you? </p> </body> </html> ``` 這是輸出。 ## C# `HttpClient` HEAD 請求 如果將使用 HTTP GET 方法請求指定的資源,則 HTTP HEAD 方法請求返回的標頭。 `Program.cs` ```cs using System; using System.Net.Http; using System.Threading.Tasks; namespace HttpClientHead { class Program { static async Task Main(string[] args) { var url = "http://webcode.me"; using var client = new HttpClient(); var result = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, url)); Console.WriteLine(result); } } } ``` 該示例發出 HEAD 請求。 ```cs $ dotnet run StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers: { Server: nginx/1.6.2 Date: Sat, 12 Oct 2019 19:55:14 GMT Connection: keep-alive ETag: "5d32ffc5-15c" Accept-Ranges: bytes Content-Type: text/html Content-Length: 348 Last-Modified: Sat, 20 Jul 2019 11:49:25 GMT } ``` 這是響應的標題字段。 ## C# `HttpClient` POST 請求 HTTP POST 方法將數據發送到服務器。 請求正文的類型由`Content-Type`標頭指示。 ```cs $ dotnet add package Newtonsoft.Json ``` 我們需要添加`Newtonsoft.Json`包來處理 JSON 數據。 `Program.cs` ```cs using System; using System.Text; using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; namespace HttpClientPost { class Person { public string Name { get; set; } public string Occupation { get; set; } public override string ToString() { return $"{Name}: {Occupation}"; } } class Program { static async Task Main(string[] args) { var person = new Person(); person.Name = "John Doe"; person.Occupation = "gardener"; var json = JsonConvert.SerializeObject(person); var data = new StringContent(json, Encoding.UTF8, "application/json"); var url = "https://httpbin.org/post"; using var client = new HttpClient(); var response = await client.PostAsync(url, data); string result = response.Content.ReadAsStringAsync().Result; Console.WriteLine(result); } } } ``` 在示例中,我們將 POST 請求發送到`https://httpbin.org/post`網站,該網站是面向開發者的在線測試服務。 ```cs var person = new Person(); person.Name = "John Doe"; person.Occupation = "gardener"; var json = JsonConvert.SerializeObject(person); var data = new StringContent(json, Encoding.UTF8, "application/json"); ``` 我們借助`Newtonsoft.Json`包將對象轉換為 JSON 數據。 ```cs var response = await client.PostAsync(url, data); ``` 我們使用`PostAsync()`方法發送異步 POST 請求。 ```cs string result = response.Content.ReadAsStringAsync().Result; Console.WriteLine(result); ``` 我們讀取返回的數據并將其打印到控制臺。 ```cs $ dotnet run { "args": {}, "data": "{\"Name\":\"John Doe\",\"Occupation\":\"gardener\"}", "files": {}, "form": {}, "headers": { "Content-Length": "43", "Content-Type": "application/json; charset=utf-8", "Host": "httpbin.org" }, "json": { "Name": "John Doe", "Occupation": "gardener" }, ... "url": "https://httpbin.org/post" } ``` This is the output. ## C# `HttpClient` JSON 請求 JSON(JavaScript 對象表示法)是一種輕量級的數據交換格式。 這種格式對于人類來說很容易讀寫,對于機器來說,解析和生成都很容易。 它是 XML 的較不冗長且更易讀的替代方案。 JSON 的官方互聯網媒體類型為`application/json`。 `Program.cs` ```cs using System; using System.Threading.Tasks; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using Newtonsoft.Json; namespace HttpClientJson { class Contributor { public string Login { get; set; } public short Contributions { get; set; } public override string ToString() { return $"{Login,20}: {Contributions} contributions"; } } class Program { private static async Task Main() { using var client = new HttpClient(); client.BaseAddress = new Uri("https://api.github.com"); client.DefaultRequestHeaders.Add("User-Agent", "C# console program"); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); var url = "repos/symfony/symfony/contributors"; HttpResponseMessage response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); var resp = await response.Content.ReadAsStringAsync(); List<Contributor> contributors = JsonConvert.DeserializeObject<List<Contributor>>(resp); contributors.ForEach(Console.WriteLine); } } } ``` 該示例生成對 Github 的 GET 請求。 它找出了 Symfony 框架的主要貢獻者。 它使用`Newtonsoft.Json`處理 JSON。 ```cs client.DefaultRequestHeaders.Add("User-Agent", "C# console program"); ``` 在請求標頭中,我們指定用戶代理。 ```cs client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); ``` 在`accept`標頭值中,我們告訴 JSON 是可接受的響應類型。 ```cs var url = "repos/symfony/symfony/contributors"; HttpResponseMessage response = await client.GetAsync(url); var resp = await response.Content.ReadAsStringAsync(); ``` 我們生成一個請求并異步讀取內容。 ```cs List<Contributor> contributors = JsonConvert.DeserializeObject<List<Contributor>>(resp); contributors.ForEach(Console.WriteLine); ``` 我們使用`JsonConvert.DeserializeObject()`方法將 JSON 響應轉換為`Contributor`對象的列表。 ## C# `HttpClient`下載圖像 `GetByteArrayAsync()`將 GET 請求發送到指定的 Uri,并在異步操作中將響應主體作為字節數組返回。 `Program.cs` ```cs using System; using System.IO; using System.Net.Http; using System.Threading.Tasks; namespace HttpClientDownloadImage { class Program { static async Task Main(string[] args) { using var httpClient = new HttpClient(); var url = "http://webcode.me/favicon.ico"; byte[] imageBytes = await httpClient.GetByteArrayAsync(url); string documentsPath = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal); string localFilename = "favicon.ico"; string localPath = Path.Combine(documentsPath, localFilename); File.WriteAllBytes(localPath, imageBytes); } } } ``` 在示例中,我們從`webcode.me`網站下載圖像。 圖像被寫入用戶的`Documents`文件夾。 ```cs byte[] imageBytes = await httpClient.GetByteArrayAsync(url); ``` `GetByteArrayAsync()`將圖像作為字節數組返回。 ```cs string documentsPath = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal); ``` 我們用`GetFolderPath()`方法確定`Documents`文件夾。 ```cs File.WriteAllBytes(localPath, imageBytes); ``` 使用`File.WriteAllBytes()`方法將字節寫入磁盤。 ## C# `HttpClient` 基本認證 在 HTTP 協議中,基本訪問認證是 HTTP 用戶代理(例如 Web 瀏覽器或控制臺應用)在發出請求時提供用戶名和密碼的方法。 在基本 HTTP 認證中,請求包含`Authorization: Basic <credentials>`形式的標頭字段,其中憑據是由單個冒號`:`連接的 id 和密碼的 base64 編碼。 > **注意**:憑證未加密; 因此,必須將 HTTP 基本認證與 HTTPS 協議一起使用。 HTTP 基本認證是用于實現對 Web 資源的訪問控制的最簡單技術。 它不需要 cookie,會話標識符或登錄頁面; 相反,HTTP 基本認證使用 HTTP 標頭中的標準字段。 `Program.cs` ```cs using System; using System.Text; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace HttpClientAuth { class Program { static async Task Main(string[] args) { var userName = "user7"; var passwd = "passwd"; var url = "https://httpbin.org/basic-auth/user7/passwd"; using var client = new HttpClient(); var authToken = Encoding.ASCII.GetBytes($"{userName}:{passwd}"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken)); var result = await client.GetAsync(url); var content = await result.Content.ReadAsStringAsync(); Console.WriteLine(content); } } } ``` 該示例將憑據發送到`httpbin.org`網站。 ```cs var authToken = Encoding.ASCII.GetBytes($"{userName}:{passwd}"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken)); ``` 在這里,我們構建認證標頭。 ```cs var url = "https://httpbin.org/basic-auth/user7/passwd"; ``` 該 URL 包含認證詳細信息,因為我們在`httpbin.org`網站上對其進行了測試。 這樣,我們不需要設置自己的服務器。 當然,認證詳細信息永遠不會放在 URL 中。 ```cs $ dotnet run { "authenticated": true, "user": "user7" } ``` This is the output. 在本教程中,我們使用 C# `HttpClient`創建 HTTP 請求。 您可能也對以下相關教程感興趣: [C# 教程](/lang/csharp/), [MySQL C# 教程](/db/mysqlcsharptutorial/), [C# 中的日期和時間](/articles/csharpdatetime/), [C# ](/articles/csharpreadwebpage/)或 [C# Winforms 教程](/gui/csharpwinforms/)。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看