1、命名空间using Flurl;
using Flurl.Http;
2、使用Nuget安装引用Flurl.Http(Fluent HTTP)
1)使用Nuget界面管理器
2)使用Package Manager命令安装PM> Install-Package Flurl.Http -Version 2.4.2
3)使用.NET CLI命令安装> dotnet add package Flurl.Http --version 2.4.2
3、执行GET和HEAD请求响应HttpResponseMessagevar getResp = await "".GetAsync();
var headResp = await "".HeadAsync();
3、获取请求JSON数据
从JSON API获取强类型的poco对象:T poco = await "".GetJsonAsync();
当创建类来匹配JSON时,非通用版本返回一个dynamic:dynamic d = await "".GetJsonAsync();
从一个返回JSON数组的API获取一个动态列表:var list = await "".GetJsonListAsync();
4、获取请求strings, bytes, 和streamsstring text = await "/readme.txt".GetStringAsync();
byte[] bytes = await "/image.jpg".GetBytesAsync();
Stream stream = await "/music.mp3".GetStreamAsync();
5、下载文件// filename is optional here; it will default to the remote file name
var path = await "/image.jpg"
.DownloadFileAsync("c:\\downloads", filename);
6、Post提交数据(JSON、Html Form)
POST提交JSON数据await "".PostJsonAsync(new { a = 1, b = 2 });
模拟HTML表单post提交await "/login".PostUrlEncodedAsync(new {
user = "user",
pass = "pass"
});
上述Post方法返回一个任务。当然,您可能希望在响应体中返回一些数据:T poco = await url.PostJsonAsync(data).ReceiveJson();
dynamic d = await url.PostUrlEncodedAsync(data).ReceiveJson();
string s = await url.PostUrlEncodedAsync(data).ReceiveString();
7、配置http请求头(header)// one:
await url.WithHeader("Accept", "text/plain").GetJsonAsync();
// multiple:
await url.WithHeaders(new { Accept = "text/plain", User_Agent = "Flurl" }).GetJsonAsync();
在上面的第二个示例中,User_Agent将自动呈现为User-Agent标题名称。(连字符在标头名称中非常常见,但在C#标识符中不允许;下划线,恰恰相反)。await url.WithBasicAuth("username", "password").GetJsonAsync();
await url.WithOAuthBearerToken("mytoken").GetJsonAsync();
8、配置Fluent HTTP (Flurl)
设置超时(timeout)时间await url.WithTimeout(10).DownloadFileAsync(); // 10 seconds
await url.WithTimeout(TimeSpan.FromMinutes(2)).DownloadFileAsync();
设置cookies// one:
await url.WithCookie("name", "value", expDate).HeadAsync();
// multiple:
await url.WithCookies(new { c1 = 1, c2 = 2 }, expDate).HeadAsync();
// date is optional; excluding it makes it a session cookie.
取消请求var cts = new CancellationTokenSource();
var task = url.GetAsync(cts.Token);
...
cts.Cancel();
一些不太常见的场景:// 使用 "raw" .Http.HttpContent object
await url.PostAsync(httpContent);
// 使用HttpMethod指定请求方式
await url.SendJsonAsync(HttpMethod.Options, poco);
// 执行更复杂配置的请求
await url.SendAsync(
HttpMethod.Trace,
httpContent, // optional
cancellationToken, // optional
HttpCompletionOption.ResponseHeaderRead); // optional
相关文档: