日韩欧美人妻无码精品白浆,夜夜嗨AV免费入口,国产欧美官网在线看,高校回应聋哑女生因长相完美被质疑

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

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

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

這個完全沒必要自己寫吧,直接用來源類庫就行了,要不讓封裝太多,有一個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 核心概念與實現(xiàn)解析

WebRequest 是網(wǎng)絡編程中用于處理HTTP/HTTPS請求的核心機制,其在不同開發(fā)環(huán)境和編程語言中存在多種實現(xiàn)形式。以下是主要分類及技術要點:


WebRequest 的核心功能

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

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

二、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 請求和接收響應的現(xiàn)代化工具,支持高性能、異步操作及靈活的配置?。以下是其關鍵特性與使用要點:


核心特性?

  1. ?異步支持?

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

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

  2. ?連接池管理?

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

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