C# Http調(diào)用詳細(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. 主要流程
- 建立連接:
HttpClient內(nèi)部通過TCP協(xié)議與目標(biāo)服務(wù)器建立連接(通常通過Socket)。 - 發(fā)送請求:構(gòu)造HTTP請求報文(包括請求行、請求頭、請求體)。
- 等待響應(yīng):服務(wù)器返回HTTP響應(yīng)報文(包括響應(yīng)行、響應(yīng)頭、響應(yīng)體)。
- 讀取響應(yīng):
HttpClient讀取響應(yīng)內(nèi)容,供程序處理。 - 關(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)文章
Unity UGUI的ContentSizeFitter內(nèi)容尺寸適應(yīng)器組件使用示例
這篇文章主要為大家介紹了Unity UGUI的ContentSizeFitter內(nèi)容尺寸適應(yīng)器組件使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08
C#實現(xiàn)圖表中鼠標(biāo)移動并顯示數(shù)據(jù)
這篇文章主要為大家詳細(xì)介紹了C#實現(xiàn)圖表中鼠標(biāo)移動并顯示數(shù)據(jù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02
C#?使用EntityFramework?CodeFirst?創(chuàng)建PostgreSQL數(shù)據(jù)庫的詳細(xì)過程
這篇文章主要介紹了C#使用EntityFramework?CodeFirst創(chuàng)建PostgreSQL數(shù)據(jù)庫的過程,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07
C#實現(xiàn)gRPC服務(wù)和調(diào)用示例詳解
gRPC?是一種與語言無關(guān)的高性能遠(yuǎn)程過程調(diào)用?(RPC)?框架,這篇文章主要為大家詳細(xì)介紹了C#如何實現(xiàn)gRPC服務(wù)和調(diào)用,需要的可以參考一下2024-01-01
在C#中調(diào)用Python代碼的兩種實現(xiàn)方式
這篇文章主要介紹了在C#中調(diào)用Python代碼的兩種實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-03-03

