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

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

admin
2025年1月2日 11:29 本文热度 2900

1.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(); }}

2.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();}


阅读原文:原文链接


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