最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C# Http調(diào)用詳細(xì)代碼

 更新時間:2025年11月17日 10:55:48   作者:猩火燎猿  
本文介紹了C#中使用HttpClient類進行HTTP請求的常用方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

一、原理講解

1. HTTP調(diào)用的基本原理

HTTP調(diào)用本質(zhì)上是:

  • 客戶端(你的C#程序)向服務(wù)器通過網(wǎng)絡(luò)發(fā)送HTTP請求(如GET、POST等),
  • 服務(wù)器接收請求并處理,
  • 然后把響應(yīng)(數(shù)據(jù)、狀態(tài)碼等)返回給客戶端。

在C#中,最常用的HTTP調(diào)用類庫是 HttpClient(.NET Framework 4.5+自帶),它封裝了底層的Socket通信和HTTP協(xié)議細(xì)節(jié),使開發(fā)者可以更簡單地發(fā)起網(wǎng)絡(luò)請求。

2. 主要流程

  1. 建立連接HttpClient內(nèi)部通過TCP協(xié)議與目標(biāo)服務(wù)器建立連接(通常通過Socket)。
  2. 發(fā)送請求:構(gòu)造HTTP請求報文(包括請求行、請求頭、請求體)。
  3. 等待響應(yīng):服務(wù)器返回HTTP響應(yīng)報文(包括響應(yīng)行、響應(yīng)頭、響應(yīng)體)。
  4. 讀取響應(yīng)HttpClient讀取響應(yīng)內(nèi)容,供程序處理。
  5. 關(guān)閉連接:連接可以復(fù)用(Keep-Alive),也可關(guān)閉。

3. 底層原理簡述

  • HttpClient基于HttpWebRequest/HttpWebResponse(.NET Core和.NET 5+底層有優(yōu)化)。
  • 網(wǎng)絡(luò)通信實際是通過Socket進行數(shù)據(jù)收發(fā)。
  • HTTP協(xié)議規(guī)定了請求和響應(yīng)的格式,HttpClient負(fù)責(zé)封裝和解析。

4. 代碼示例與報文結(jié)構(gòu)

以GET請求為例:

代碼

using System;
using System.Net.Http;
using System.Threading.Tasks;
 
class Program
{
    public static async Task Main(string[] args)
    {
        using (HttpClient client = new HttpClient())
        {
            HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
            string content = await response.Content.ReadAsStringAsync();
            Console.WriteLine(content);
        }
    }
}

實際HTTP報文

請求報文:

GET /posts/1 HTTP/1.1
Host: jsonplaceholder.typicode.com
User-Agent: ...
Accept: ...
Connection: keep-alive
...

響應(yīng)報文:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 292
...

{
  "userId": 1,
  "id": 1,
  "title": "...",
  "body": "..."
}

5. 關(guān)鍵點

  • 請求方式:決定HTTP請求的類型(GET/POST/PUT/DELETE等)。
  • 請求頭/響應(yīng)頭:包含元數(shù)據(jù)(如Content-Type、Authorization等)。
  • 請求體/響應(yīng)體:實際傳輸?shù)臄?shù)據(jù)(如JSON、文本、文件等)。
  • 狀態(tài)碼:服務(wù)器響應(yīng)的處理結(jié)果(如200、404、500等)。

6. 總結(jié)

  • C#通過HttpClient等類庫,底層用Socket實現(xiàn)HTTP協(xié)議的數(shù)據(jù)收發(fā)。
  • HttpClient負(fù)責(zé)封裝HTTP報文,簡化開發(fā)流程。
  • HTTP調(diào)用的本質(zhì)是:構(gòu)造請求 → 發(fā)送 → 等待響應(yīng) → 解析響應(yīng)

二、完整代碼示例

1. 引入命名空間

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

2. GET請求

public static async Task HttpGetAsync()
{
    using (HttpClient client = new HttpClient())
    {
        // 設(shè)置請求頭(可選)
        client.DefaultRequestHeaders.Add("User-Agent", "C# App");
 
        // 發(fā)送GET請求
        HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
 
        // 判斷是否成功
        if (response.IsSuccessStatusCode)
        {
            string content = await response.Content.ReadAsStringAsync();
            Console.WriteLine("GET請求結(jié)果:");
            Console.WriteLine(content);
        }
        else
        {
            Console.WriteLine($"GET請求失敗,狀態(tài)碼:{response.StatusCode}");
        }
    }
}

3. POST請求(發(fā)送JSON)

public static async Task HttpPostAsync()
{
    using (HttpClient client = new HttpClient())
    {
        // 構(gòu)造要發(fā)送的數(shù)據(jù)
        string json = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
        StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
 
        // 發(fā)送POST請求
        HttpResponseMessage response = await client.PostAsync("https://jsonplaceholder.typicode.com/posts", content);
 
        // 判斷是否成功
        if (response.IsSuccessStatusCode)
        {
            string result = await response.Content.ReadAsStringAsync();
            Console.WriteLine("POST請求結(jié)果:");
            Console.WriteLine(result);
        }
        else
        {
            Console.WriteLine($"POST請求失敗,狀態(tài)碼:{response.StatusCode}");
        }
    }
}

4. 主函數(shù)調(diào)用示例

public static async Task Main(string[] args)
{
    await HttpGetAsync();
    await HttpPostAsync();
}

5. 完整代碼示例

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
 
class Program
{
    public static async Task HttpGetAsync()
    {
        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("User-Agent", "C# App");
            HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
            if (response.IsSuccessStatusCode)
            {
                string content = await response.Content.ReadAsStringAsync();
                Console.WriteLine("GET請求結(jié)果:");
                Console.WriteLine(content);
            }
            else
            {
                Console.WriteLine($"GET請求失敗,狀態(tài)碼:{response.StatusCode}");
            }
        }
    }
 
    public static async Task HttpPostAsync()
    {
        using (HttpClient client = new HttpClient())
        {
            string json = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
            StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync("https://jsonplaceholder.typicode.com/posts", content);
            if (response.IsSuccessStatusCode)
            {
                string result = await response.Content.ReadAsStringAsync();
                Console.WriteLine("POST請求結(jié)果:");
                Console.WriteLine(result);
            }
            else
            {
                Console.WriteLine($"POST請求失敗,狀態(tài)碼:{response.StatusCode}");
            }
        }
    }
 
    public static async Task Main(string[] args)
    {
        await HttpGetAsync();
        await HttpPostAsync();
    }
}

6. 添加自定義請求頭(如Token)

public static async Task HttpGetWithTokenAsync()
{
    using (HttpClient client = new HttpClient())
    {
        // 添加Bearer Token
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "your_token_here");
        
        HttpResponseMessage response = await client.GetAsync("https://api.example.com/data");
        string result = await response.Content.ReadAsStringAsync();
        Console.WriteLine(result);
    }
}

7. 發(fā)送表單數(shù)據(jù)(application/x-www-form-urlencoded)

public static async Task HttpPostFormAsync()
{
    using (HttpClient client = new HttpClient())
    {
        var formData = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("username", "test"),
            new KeyValuePair<string, string>("password", "123456")
        });
 
        HttpResponseMessage response = await client.PostAsync("https://httpbin.org/post", formData);
        string result = await response.Content.ReadAsStringAsync();
        Console.WriteLine(result);
    }
}

8. 上傳文件(multipart/form-data)

public static async Task HttpPostFileAsync()
{
    using (HttpClient client = new HttpClient())
    {
        using (var multipartFormContent = new MultipartFormDataContent())
        {
            // 添加文件
            var fileStream = System.IO.File.OpenRead("test.txt");
            multipartFormContent.Add(new StreamContent(fileStream), name: "file", fileName: "test.txt");
 
            // 添加其他表單字段
            multipartFormContent.Add(new StringContent("value1"), "field1");
 
            HttpResponseMessage response = await client.PostAsync("https://httpbin.org/post", multipartFormContent);
            string result = await response.Content.ReadAsStringAsync();
            Console.WriteLine(result);
        }
    }
}

9. 設(shè)置超時和異常處理

public static async Task HttpGetWithTimeoutAsync()
{
    using (HttpClient client = new HttpClient())
    {
        client.Timeout = TimeSpan.FromSeconds(5); // 設(shè)置超時時間
 
        try
        {
            HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
            string content = await response.Content.ReadAsStringAsync();
            Console.WriteLine(content);
        }
        catch (TaskCanceledException ex)
        {
            Console.WriteLine("請求超時: " + ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("請求異常: " + ex.Message);
        }
    }
}

10. 反序列化JSON響應(yīng)為對象

你可以使用 System.Text.Json 或 Newtonsoft.Json,這里用自帶的 System.Text.Json。

using System.Text.Json;
 
public class Post
{
    public int userId { get; set; }
    public int id { get; set; }
    public string title { get; set; }
    public string body { get; set; }
}
 
public static async Task HttpGetDeserializeAsync()
{
    using (HttpClient client = new HttpClient())
    {
        HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
        string content = await response.Content.ReadAsStringAsync();
 
        // 反序列化為對象
        var post = JsonSerializer.Deserialize<Post>(content);
        Console.WriteLine($"標(biāo)題: {post.title}, 內(nèi)容: {post.body}");
    }
}

到此這篇關(guān)于C# Http調(diào)用詳細(xì)代碼的文章就介紹到這了,更多相關(guān)C# Http調(diào)用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

盐山县| 宣威市| 修水县| 土默特左旗| 江源县| 恭城| 商丘市| 西盟| 翁牛特旗| 秦安县| 左云县| 长春市| 若羌县| 无为县| 南丹县| 当阳市| 江门市| 监利县| 永川市| 房山区| 江安县| 阆中市| 长葛市| 晋江市| 靖宇县| 永川市| 伊宁县| 大宁县| 武山县| 宁乡县| 左权县| 比如县| 郸城县| 苗栗县| 溆浦县| 新绛县| 阜城县| 红安县| 长阳| 巴彦淖尔市| 买车|