.net core基於HttpClient實現的網路請求庫

胖紙不爭發表於2023-04-01

Soda.Http

基於HttpClient封裝的 Http 請求庫。如果有什麼好想法,可以提 Issue 或者 Pr。,如果想要使用,直接在nuget搜尋Soda.Http即可。

Github專案地址:Soda.Http

用法

1 預載

預載配置並不是必須的,但是有助於我們進行一些通用基礎設定,例如Headers、Accept、BaseUrl等等。

配置BaseUrl之後,可以直接使用QSodaHttp.Uri()代替QSodaHttp.Url(),直接填寫介面即可。

AspNetCore中:

services.AddSodaHttp(opts =>
{
    opts.BaseUrl = "http://localhost:8080/";
    opts.Accept = new[]
    {
        "application/json",
        "text/plain",
        "*/*"
    };
    opts.EnableCompress = false;
    opts.Headers = new[]{
        ("X-Ca-Test", "key")
    };
});

較為通用的寫法,程式構建時:

QSodaHttp.AddSodaHttp(opts =>
{
    opts.BaseUrl = "http://localhost:8080/";
    opts.Accept = new[]
    {
        "application/json",
        "text/plain",
        "*/*"
    };
    opts.EnableCompress = false;
    opts.Headers = new[]{
        ("X-Ca-Test", "key")
    };
})

2 全域性配置 Authentication

有時需要全域性配置 Authentication,如果在程式碼中請求中獨立配置了 Authentication 則會覆蓋全域性 Authentication

QSodaHttp.InitAuthentication("Bearer", "Values");

如果你是塞到 Header 裡的這種做法

QSodaHttp.AddHeader("X-Ca-Key", "Values");

3 Http 請求

3.1 QSodaHttp

API 示例:

var result = await QSodaHttp.Url("https://www.baidu.com/")
    .Header("X-Ca-Key", "XXX")
    .Authentication("Bearer", "XXX")
    .Params(new { Id = "123456" })
    .Body(new { })
    // .Form(...)
    // .File(...)
    .PostAsync<string>();

簡單示例:

// 配置BaseUrl
var services = new ServiceCollection();
services.AddSodaHttp(opts =>
{
    opts.EnableCompress = false;
    opts.BaseUrl = "http://localhost:5050/";
});
var res = await QSodaHttp.Uri("/Test/Get").Params(new { Id = "123456" }).GetAsync<object>();
var res = await QSodaHttp.Uri("/Test/TestGetResult").Params(new { Id = "123456", Ids = new[] { "123", "456" } }).GetAsync<object>();
var res = await QSodaHttp.Uri("/Test/Post").Body(new { Id = "123456", Ids = new[] { "123", "456" } }).PostAsync<object>();
var res = await QSodaHttp.Uri("/Test/PostResult")
        .Params(new { Id = "123456", Ids = new[] { "123", "456" } })
        .Body(new { Id = "123456", Ids = new[] { "123", "456" } })
        .PostAsync<object>();
var res = await QSodaHttp.Uri("/Test/Delete").Params(new { Id = "123456" }).DeleteAsync<object>();
var res = await QSodaHttp.Uri("/Test/DeleteResult").Params(new { Id = "123456", Ids = new[] { "123", "456" } }).DeleteAsync<object>();
var res = await QSodaHttp.Uri("/Test/Put").Params(new { Id = "123456" }).PutAsync<object>();
var res = await QSodaHttp.Uri("/Test/PutResult")
        .Body(new { Id = "123456", Ids = new[] { "123", "456" } })
        .PutAsync<object>();
var res = await QSodaHttp.Uri("Patch").Params(new { Id = "123456" }).PatchAsync<object>();
var res = await QSodaHttp.Uri("PatchResult")
        .Body(new { Id = "123456", Ids = new[] { "123", "456" } })
        .PatchAsync<object>();

相關文章