這個完全沒必要自己寫吧,直接用來源類庫就行了,要不讓封裝太多,有一個Flurl這個就很好用,下面是自己寫的方法。
一、WebRequest方式
引用dll
using System.IO;
using System.Net;
using System.Threading.Tasks;
public static string HttpPost(string url, string body)
{
Encoding encoding = Encoding.UTF8;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Accept = "text/html, application/xhtml+xml, */*";
request.ContentType = "application/json";
byte[] buffer = encoding.GetBytes(body);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
public static string HttpGet(string url)
{
Encoding encoding = Encoding.UTF8;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.Accept = "text/html, application/xhtml+xml, */*";
request.ContentType = "application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
WebRequest 核心概念與實(shí)現(xiàn)解析
WebRequest 是網(wǎng)絡(luò)編程中用于處理HTTP/HTTPS請求的核心機(jī)制,其在不同開發(fā)環(huán)境和編程語言中存在多種實(shí)現(xiàn)形式。以下是主要分類及技術(shù)要點(diǎn):
WebRequest 的核心功能
?HTTP請求處理?
WebRequest 主要用于構(gòu)建HTTP請求報文(包含請求行、請求頭和請求體)?,并在服務(wù)端解析后存儲于Request對象中,便于后續(xù)參數(shù)獲取及業(yè)務(wù)處理?。同時,通過Response對象設(shè)置響應(yīng)數(shù)據(jù),由服務(wù)器按HTTP協(xié)議格式返回客戶端?。
?請求生命周期管理?
包括建立連接、處理重定向、超時控制等。例如,C#的HttpWebRequest支持設(shè)置 AllowAutoRedirect
控制重定向,Timeout
設(shè)定超時限制?。
二、HttpClient 方式
static HttpClient client = new HttpClient();
static async Task<Uri> CreateProductAsync(Product product)
{
HttpResponseMessage response = await client.PostAsJsonAsync(
"api/products", product);
response.EnsureSuccessStatusCode();
return response.Headers.Location;
}
static async Task<Product> GetProductAsync(string path)
{
Product product = null;
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
product = await response.Content.ReadAsAsync<Product>();
}
return product;
}
static async Task<Product> UpdateProductAsync(Product product)
{
HttpResponseMessage response = await client.PutAsJsonAsync(
$"api/products/{product.Id}", product);
response.EnsureSuccessStatusCode();
product = await response.Content.ReadAsAsync<Product>();
return product;
}
static async Task<HttpStatusCode> DeleteProductAsync(string id)
{
HttpResponseMessage response = await client.DeleteAsync(
$"api/products/{id}");
return response.StatusCode;
}
static async Task RunAsync()
{
client.BaseAddress = new Uri("http://localhost:64195/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
try
{
Product product = new Product
{
Name = "Gizmo",
Price = 100,
Category = "Widgets"
};
var url = await CreateProductAsync(product);
Console.WriteLine($"Created at {url}");
product = await GetProductAsync(url.PathAndQuery);
ShowProduct(product);
Console.WriteLine("Updating price...");
product.Price = 80;
await UpdateProductAsync(product);
product = await GetProductAsync(url.PathAndQuery);
ShowProduct(product);
var statusCode = await DeleteProductAsync(product.Id);
Console.WriteLine($"Deleted (HTTP Status = {(int)statusCode})");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
?C# HttpClient 核心功能與使用指南?
HttpClient 是 .NET 中用于發(fā)送 HTTP 請求和接收響應(yīng)的現(xiàn)代化工具,支持高性能、異步操作及靈活的配置?。以下是其關(guān)鍵特性與使用要點(diǎn):
核心特性?
?異步支持?
- 所有方法均原生支持
async/await
,適用于高并發(fā)場景(如微服務(wù)通信)?。 - 示例:
var response = await client.GetAsync("https://api.example.com/data");
?連接池管理?
- 每個
HttpClient
實(shí)例維護(hù)獨(dú)立的連接池,復(fù)用 TCP 連接以提升性能?。 - ?注意?:避免頻繁創(chuàng)建實(shí)例,推薦通過單例或
IHttpClientFactory
管理?。
?請求配置?
- 支持自定義請求頭、超時時間、認(rèn)證方式(如 Basic、JWT、Cookie)?。
- 示例(設(shè)置請求頭):
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", "your_jwt_token");
?數(shù)據(jù)傳輸格式?
- 支持 JSON、表單、文件上傳等格式,需通過
StringContent
、MultipartFormDataContent
等類封裝數(shù)據(jù)?。
該文章在 2025/5/14 9:18:36 編輯過