超碰人人人人人,亚洲AV午夜福利精品一区二区,亚洲欧美综合区丁香五月1区,日韩欧美亚洲系列

LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發(fā)文檔 其他文檔  
 
網(wǎng)站管理員

C#請求WebApi接口常用的兩種方式

admin
2025年5月13日 23:17 本文熱度 38

這個完全沒必要自己寫吧,直接用來源類庫就行了,要不讓封裝太多,有一個Flurl這個就很好用,下面是自己寫的方法。

一、WebRequest方式

引用dll 

using System.IO;using System.Net;using System.Threading.Tasks;
//Postpublic 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(); }}
//GETpublic 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 的核心功能

  1. ?HTTP請求處理?
    WebRequest 主要用于構(gòu)建HTTP請求報文(包含請求行、請求頭和請求體)?,并在服務(wù)端解析后存儲于Request對象中,便于后續(xù)參數(shù)獲取及業(yè)務(wù)處理?。同時,通過Response對象設(shè)置響應(yīng)數(shù)據(jù),由服務(wù)器按HTTP協(xié)議格式返回客戶端?

  2. ?請求生命周期管理?
    包括建立連接、處理重定向、超時控制等。例如,C#的HttpWebRequest支持設(shè)置 AllowAutoRedirect 控制重定向,Timeout 設(shè)定超時限制?。

二、HttpClient 方式

static HttpClient client = new HttpClient();
//根據(jù) ID 獲取產(chǎn)品static async Task<Uri> CreateProductAsync(Product product){ HttpResponseMessage response = await client.PostAsJsonAsync( "api/products", product); response.EnsureSuccessStatusCode();
// return URI of the created resource. return response.Headers.Location;}
//創(chuàng)建新產(chǎn)品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;}
//更新產(chǎn)品static async Task<Product> UpdateProductAsync(Product product){ HttpResponseMessage response = await client.PutAsJsonAsync( $"api/products/{product.Id}", product); response.EnsureSuccessStatusCode();
// Deserialize the updated product from the response body. product = await response.Content.ReadAsAsync<Product>(); return product;}
//刪除產(chǎn)品static async Task<HttpStatusCode> DeleteProductAsync(string id){ HttpResponseMessage response = await client.DeleteAsync( $"api/products/{id}"); return response.StatusCode;}
HttpClient 異步調(diào)用
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}");        // Get the product        product = await GetProductAsync(url.PathAndQuery);        ShowProduct(product);        // Update the product        Console.WriteLine("Updating price...");        product.Price = 80;        await UpdateProductAsync(product);        // Get the updated product        product = await GetProductAsync(url.PathAndQuery);        ShowProduct(product);        // Delete the 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):


核心特性?

  1. ?異步支持?

    • 所有方法均原生支持 async/await,適用于高并發(fā)場景(如微服務(wù)通信)?。
    • 示例:
      csharpCopy Code

      var response = await client.GetAsync("https://api.example.com/data");

  2. ?連接池管理?

    • 每個 HttpClient 實(shí)例維護(hù)獨(dú)立的連接池,復(fù)用 TCP 連接以提升性能?
    • ?注意?:避免頻繁創(chuàng)建實(shí)例,推薦通過單例或 IHttpClientFactory 管理?。
  3. ?請求配置?

    • 支持自定義請求頭、超時時間、認(rèn)證方式(如 Basic、JWT、Cookie)?。
    • 示例(設(shè)置請求頭):
      csharpCopy Code

      client.DefaultRequestHeaders.Authorization = 
          new AuthenticationHeaderValue("Bearer""your_jwt_token");

  4. ?數(shù)據(jù)傳輸格式?

    • 支持 JSON、表單、文件上傳等格式,需通過 StringContent、MultipartFormDataContent 等類封裝數(shù)據(jù)?。

該文章在 2025/5/14 9:18:36 編輯過
關(guān)鍵字查詢
相關(guān)文章
正在查詢...
點(diǎn)晴ERP是一款針對中小制造業(yè)的專業(yè)生產(chǎn)管理軟件系統(tǒng),系統(tǒng)成熟度和易用性得到了國內(nèi)大量中小企業(yè)的青睞。
點(diǎn)晴PMS碼頭管理系統(tǒng)主要針對港口碼頭集裝箱與散貨日常運(yùn)作、調(diào)度、堆場、車隊、財務(wù)費(fèi)用、相關(guān)報表等業(yè)務(wù)管理,結(jié)合碼頭的業(yè)務(wù)特點(diǎn),圍繞調(diào)度、堆場作業(yè)而開發(fā)的。集技術(shù)的先進(jìn)性、管理的有效性于一體,是物流碼頭及其他港口類企業(yè)的高效ERP管理信息系統(tǒng)。
點(diǎn)晴WMS倉儲管理系統(tǒng)提供了貨物產(chǎn)品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質(zhì)期管理,貨位管理,庫位管理,生產(chǎn)管理,WMS管理系統(tǒng),標(biāo)簽打印,條形碼,二維碼管理,批號管理軟件。
點(diǎn)晴免費(fèi)OA是一款軟件和通用服務(wù)都免費(fèi),不限功能、不限時間、不限用戶的免費(fèi)OA協(xié)同辦公管理系統(tǒng)。
Copyright 2010-2025 ClickSun All Rights Reserved