LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

C#请求WebApi接口常用的两种方式

admin
2025年5月13日 23:17 本文热度 40

这个完全没必要自己写吧,直接用来源类库就行了,要不让封装太多,有一个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 核心概念与实现解析

WebRequest 是网络编程中用于处理HTTP/HTTPS请求的核心机制,其在不同开发环境和编程语言中存在多种实现形式。以下是主要分类及技术要点:


WebRequest 的核心功能

  1. HTTP请求处理
    WebRequest 主要用于构建HTTP请求报文(包含请求行、请求头和请求体)‌,并在服务端解析后存储于Request对象中,便于后续参数获取及业务处理‌。同时,通过Response对象设置响应数据,由服务器按HTTP协议格式返回客户端‌

  2. 请求生命周期管理
    包括建立连接、处理重定向、超时控制等。例如,C#的HttpWebRequest支持设置 AllowAutoRedirect 控制重定向,Timeout 设定超时限制‌

二、HttpClient 方式

static HttpClient client = new HttpClient();
//根据 ID 获取产品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;}
//创建新产品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();
// Deserialize the updated product from the response body. 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;}
HttpClient 异步调用
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 中用于发送 HTTP 请求和接收响应的现代化工具,支持高性能、异步操作及灵活的配置‌。以下是其关键特性与使用要点:


核心特性

  1. 异步支持

    • 所有方法均原生支持 async/await,适用于高并发场景(如微服务通信)‌
    • 示例:
      csharpCopy Code

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

  2. 连接池管理

    • 每个 HttpClient 实例维护独立的连接池,复用 TCP 连接以提升性能‌
    • 注意‌:避免频繁创建实例,推荐通过单例或 IHttpClientFactory 管理‌
  3. 请求配置

    • 支持自定义请求头、超时时间、认证方式(如 Basic、JWT、Cookie)‌
    • 示例(设置请求头):
      csharpCopy Code

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

  4. 数据传输格式

    • 支持 JSON、表单、文件上传等格式,需通过 StringContentMultipartFormDataContent 等类封装数据‌

该文章在 2025/5/14 9:18:36 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2025 ClickSun All Rights Reserved