C# Http調(diào)用詳細(xì)代碼
一、原理講解
1. HTTP調(diào)用的基本原理
HTTP調(diào)用本質(zhì)上是:
- 客戶端(你的C#程序)向服務(wù)器通過(guò)網(wǎng)絡(luò)發(fā)送HTTP請(qǐng)求(如GET、POST等),
- 服務(wù)器接收請(qǐng)求并處理,
- 然后把響應(yīng)(數(shù)據(jù)、狀態(tài)碼等)返回給客戶端。
在C#中,最常用的HTTP調(diào)用類庫(kù)是 HttpClient(.NET Framework 4.5+自帶),它封裝了底層的Socket通信和HTTP協(xié)議細(xì)節(jié),使開發(fā)者可以更簡(jiǎn)單地發(fā)起網(wǎng)絡(luò)請(qǐng)求。
2. 主要流程
- 建立連接:
HttpClient內(nèi)部通過(guò)TCP協(xié)議與目標(biāo)服務(wù)器建立連接(通常通過(guò)Socket)。 - 發(fā)送請(qǐng)求:構(gòu)造HTTP請(qǐng)求報(bào)文(包括請(qǐng)求行、請(qǐng)求頭、請(qǐng)求體)。
- 等待響應(yīng):服務(wù)器返回HTTP響應(yīng)報(bào)文(包括響應(yīng)行、響應(yīng)頭、響應(yīng)體)。
- 讀取響應(yīng):
HttpClient讀取響應(yīng)內(nèi)容,供程序處理。 - 關(guān)閉連接:連接可以復(fù)用(Keep-Alive),也可關(guān)閉。
3. 底層原理簡(jiǎn)述
HttpClient基于HttpWebRequest/HttpWebResponse(.NET Core和.NET 5+底層有優(yōu)化)。- 網(wǎng)絡(luò)通信實(shí)際是通過(guò)Socket進(jìn)行數(shù)據(jù)收發(fā)。
- HTTP協(xié)議規(guī)定了請(qǐng)求和響應(yīng)的格式,
HttpClient負(fù)責(zé)封裝和解析。
4. 代碼示例與報(bào)文結(jié)構(gòu)
以GET請(qǐng)求為例:
代碼
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);
}
}
}實(shí)際HTTP報(bào)文
請(qǐng)求報(bào)文:
GET /posts/1 HTTP/1.1 Host: jsonplaceholder.typicode.com User-Agent: ... Accept: ... Connection: keep-alive ...
響應(yīng)報(bào)文:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 292
...
{
"userId": 1,
"id": 1,
"title": "...",
"body": "..."
}
5. 關(guān)鍵點(diǎn)
- 請(qǐng)求方式:決定HTTP請(qǐng)求的類型(GET/POST/PUT/DELETE等)。
- 請(qǐng)求頭/響應(yīng)頭:包含元數(shù)據(jù)(如Content-Type、Authorization等)。
- 請(qǐng)求體/響應(yīng)體:實(shí)際傳輸?shù)臄?shù)據(jù)(如JSON、文本、文件等)。
- 狀態(tài)碼:服務(wù)器響應(yīng)的處理結(jié)果(如200、404、500等)。
6. 總結(jié)
- C#通過(guò)
HttpClient等類庫(kù),底層用Socket實(shí)現(xiàn)HTTP協(xié)議的數(shù)據(jù)收發(fā)。 HttpClient負(fù)責(zé)封裝HTTP報(bào)文,簡(jiǎn)化開發(fā)流程。- HTTP調(diào)用的本質(zhì)是:構(gòu)造請(qǐng)求 → 發(fā)送 → 等待響應(yīng) → 解析響應(yīng)。
二、完整代碼示例
1. 引入命名空間
using System; using System.Net.Http; using System.Text; using System.Threading.Tasks;
2. GET請(qǐng)求
public static async Task HttpGetAsync()
{
using (HttpClient client = new HttpClient())
{
// 設(shè)置請(qǐng)求頭(可選)
client.DefaultRequestHeaders.Add("User-Agent", "C# App");
// 發(fā)送GET請(qǐng)求
HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
// 判斷是否成功
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine("GET請(qǐng)求結(jié)果:");
Console.WriteLine(content);
}
else
{
Console.WriteLine($"GET請(qǐng)求失敗,狀態(tài)碼:{response.StatusCode}");
}
}
}3. POST請(qǐng)求(發(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請(qǐng)求
HttpResponseMessage response = await client.PostAsync("https://jsonplaceholder.typicode.com/posts", content);
// 判斷是否成功
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine("POST請(qǐng)求結(jié)果:");
Console.WriteLine(result);
}
else
{
Console.WriteLine($"POST請(qǐng)求失敗,狀態(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請(qǐng)求結(jié)果:");
Console.WriteLine(content);
}
else
{
Console.WriteLine($"GET請(qǐng)求失敗,狀態(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請(qǐng)求結(jié)果:");
Console.WriteLine(result);
}
else
{
Console.WriteLine($"POST請(qǐng)求失敗,狀態(tài)碼:{response.StatusCode}");
}
}
}
public static async Task Main(string[] args)
{
await HttpGetAsync();
await HttpPostAsync();
}
}6. 添加自定義請(qǐng)求頭(如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è)置超時(shí)和異常處理
public static async Task HttpGetWithTimeoutAsync()
{
using (HttpClient client = new HttpClient())
{
client.Timeout = TimeSpan.FromSeconds(5); // 設(shè)置超時(shí)時(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("請(qǐng)求超時(shí): " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("請(qǐng)求異常: " + ex.Message);
}
}
}10. 反序列化JSON響應(yīng)為對(duì)象
你可以使用 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();
// 反序列化為對(duì)象
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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SQLite之C#版 System.Data.SQLite使用方法
這篇文章主要介紹了SQLite之C#版 System.Data.SQLite使用方法,需要的朋友可以參考下2020-10-10
C# Helper開發(fā)一個(gè)簡(jiǎn)單的端口監(jiān)控工具
C# 端口監(jiān)控 Helper 是一款基于C#語(yǔ)言的工具,這個(gè)意義在于幫助開發(fā)者快速實(shí)現(xiàn)對(duì)指定端口的監(jiān)控,以保障(觀察)網(wǎng)絡(luò)服務(wù)的正常運(yùn)行,下面我們就來(lái)看看具體實(shí)現(xiàn)方法吧2025-09-09
C#實(shí)現(xiàn)圖片放大功能的按照像素放大圖像方法
這篇文章主要介紹了C#實(shí)現(xiàn)圖片放大功能的按照像素放大圖像方法,功能非常實(shí)用,需要的朋友可以參考下2014-07-07
Unity游戲開發(fā)之炸彈人游戲的實(shí)現(xiàn)
大家小時(shí)候肯定玩過(guò)這款游戲,炸彈人也算是經(jīng)典中的經(jīng)典啦。本文將利用Unity模擬實(shí)現(xiàn)這一經(jīng)典游戲,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-03-03
C#通過(guò)NPOI操作Excel的實(shí)例代碼
C#操作Excel的方法有很多種,本文介紹了C#通過(guò)NPOI操作Excel,具有一定的參考價(jià)值,有興趣的可以了解一下。2017-01-01
C#模擬Http與Https請(qǐng)求框架類實(shí)例
這篇文章主要介紹了C#模擬Http與Https請(qǐng)求框架類,實(shí)例分析了處理http與https請(qǐng)求的方法與信息處理的技巧,需要的朋友可以參考下2014-12-12
C#使用protobuf-net進(jìn)行序列化的詳細(xì)操作
本文帶領(lǐng)大家學(xué)習(xí)C#中protobuf-net工具的另一種使用體驗(yàn),這個(gè)工具的使用體驗(yàn)屬于Code-First模式,先定義類型,并使用注解進(jìn)行標(biāo)記,不需要先編寫.proto文件,感興趣的朋友跟隨小編一起看看吧2021-11-11
C# 實(shí)現(xiàn)簡(jiǎn)易的串口監(jiān)視上位機(jī)功能附源碼下載
這篇文章主要介紹了C# 實(shí)現(xiàn)簡(jiǎn)易的串口監(jiān)視上位機(jī)功能,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11

