簡介
官方居間,flurl 是一個現代的,流利的,支持異步的,可測試的,可移植的,url 增強和 http 客戶端組件。
url 構建
現在有一個登錄的接口,地址如下:
https://www.some-api.com/login?name=Lee&pwd=123456
我们在处理这个地址的时候,会拼接 login, 然后拼接?号, 然后拼接参数,中间还要拼接& 得到最终的地址。
使用 Flurl 构建,首先需要通过 NuGet 安装 Flurl 组件。
var url = "http://www.some-api.com"
.AppendPathSegment("login")
.SetQueryParams(new
{
name = "Lee",
pwd = "123456"
});
這很簡單,這是最簡單的 get 請求,同樣的我們也可以使用 uri 的擴展方法
var url = new Uri("http://www.some-api.com").AppendPathSegment(...
http 增強
Flurl 是模块化的,所以还需要安装 Flurl.Http
using Flurl;
using Flurl.Http;
var result = await "http://www.some-api.com".AppendPathSegment("login").GetAsync();
上面的代码会发送一个 GET 请求,并返回一个IFlurlResponse,可以得到 StatusCode,Headers 等,也可以通过 GetStringAsync 和 GetJsonAsync 得到响应内容。
如果只是想獲取響應內容,我們看看 flurl 有多簡單:
T poco = await "http://api.foo.com".GetJsonAsync<T>();
string text = await "http://site.com/readme.txt".GetStringAsync();
byte[] bytes = await "http://site.com/image.jpg".GetBytesAsync();
Stream stream = await "http://site.com/music.mp3".GetStreamAsync();
post 提交
await "http://api.foo.com".PostJsonAsync(new { a = 1, b = 2 });
動態類型 dynamic
dynamic d = await "http://api.foo.com".GetJsonAsync();
設置請求標頭:
await url.WithHeader("Accept", "text/plain").GetJsonAsync();
await url.WithHeaders(new { Accept = "text/plain", User_Agent = "Flurl" }).GetJsonAsync();
基礎身份驗證
await url.WithBasicAuth("username", "password").GetJsonAsync();
OAuth 2.0
await url.WithOAuthBearerToken("mytoken").GetJsonAsync();
表單提交
await "http://site.com/login".PostUrlEncodedAsync(new {
user = "user",
pass = "pass"
});
httpclient 管理
我們通常不會創建太多的 httpclient, 過多的連接會耗盡伺服器資源,通常會拋出 socketexception 異常,大部分還是使用 httpclientfactory。
在 flurl 庫中,它是內部管理 httpclient 實例, 通常一個主機 host,會創建一個 httpclient,然後緩存來復用。
flurl 也很好的支持了 ioc 容器,你也可以在依賴注入中使用它。
總結
flurl 組件讓 http 操作變得更簡單易用,你可以在項目中嘗試使用它,其他的還有一些功能,可測試可配置等,你都可以在官網找到它的文檔。
歡迎掃碼關注我們的公眾號 【半棧程式設計師】,專注國外優秀博客的翻譯和開源項目分享。