如果是以前,想要用.NET 發起一個Http請求真的非常復雜,需要寫好幾十行代碼才行,現在好了,開源社區里面有幾款不錯的HTTP請求組件,這里我推你進來看看,這里的Demo我們就請求一個免費的API接口吧,我們先看看接口返回的數據

然后創建一個該json適配的類,你也可以用VS里面自帶的將JSON粘貼為類的功能,直接把根據json格式生成一個類,然后自己再稍加調整一下即可,這里我創建了兩個類分別為ResultResponse和Result。
public class ResultResponse
{
public int code { get; set; }
public string message { get; set; }
public Result[] result { get; set; }
}
public class Result
{
public string sid { get; set; }
public string text { get; set; }
public string type { get; set; }
public string thumbnail { get; set; }
public string video { get; set; }
public object images { get; set; }
public string up { get; set; }
public string down { get; set; }
public string forward { get; set; }
public string comment { get; set; }
public string uid { get; set; }
public string name { get; set; }
public string header { get; set; }
public string top_comments_content { get; set; }
public string top_comments_voiceuri { get; set; }
public string top_comments_uid { get; set; }
public string top_comments_name { get; set; }
public string top_comments_header { get; set; }
public string passtime { get; set; }
}
因為我這個類是自動生成的,所以命名風格有點怪,這里就先忽略,但是實際應用中一定要注意這個問題。好了下面開始實踐各個請求庫了
refit

直接通過Nuget即可安裝

這里我們新建一個名為IWebApi的接口:
public interface IWebApi
{
[Get("/getJoke?page={page}&count={count}&type={video}")]
Task<ResultResponse> GetJoke(int page,int count,string video);
}
這里的Get是refit的特性之一,里面的字符串即為請求路徑和參數
現在,我們就去調用這個接口
[HttpGet("joke")]
public async Task<ResultResponse> GetJoke()
{
var webApi = RestService.For<IWebApi>("https://api.apiopen.top/");
return await webApi.GetJoke(1,10, "video");
}
就這樣簡單的使用就可以獲取我們接口的信息了

refit為我們提供了很多特性,如果在請求時需要加Header,那么可以使用Headers這個特性。
EasyHttp
這個開源庫已經很久沒有更新了

由于我演示是用的.net core 3.1,EasyHttp不支持Core,所以這里就不演示了,我就在Github搬一些案例過來吧
var http = new HttpClient();
http.Request.Accept = HttpContentTypes.ApplicationJson;
var response = http.Get("url");
var customer = response.DynamicBody;
如果是.net framework是的同學,可以使用一下。
RestSharp
這個庫的熱度還是畢竟高,已經達到了7.5k star

這里我們就先省略Nuget安裝,直接到示例編碼
[HttpGet("joke")]
public async Task<string> GetJoke()
{
var client = new RestClient("https://api.apiopen.top");
var request = new RestRequest("/getJoke?page=1&count=2&type=video", Method.GET);
IRestResponse rest= await client.ExecuteAsync(request);
return rest.Content;
}
這里只是一個簡單的調用,它也提供了比較全面的工具方法,各位可以去官網了解一下
Flurl.Http
這個開源類庫使用起來也是非常方便的,它擴展了字符串方法,在Nuget中安裝Flurl.Http

然后一句代碼即可發起HTTP請求并序列化成對象
[HttpGet("joke")]
public async Task<ResultResponse> GetJoke()
{
return await "https://api.apiopen.top/getJoke?page=1&count=2&type=video".GetJsonAsync<ResultResponse>();
}
好了,這里只是簡單的分享4款開源的http請求組件,使用的示例也是非常簡單,并沒有對這幾個組件進行對比分析,你們在使用之前請先自行實踐對比,進行最優選擇。