1、命名空间

using Flurl;using Flurl.Http;

2、利用Nuget安装引用Flurl.Http(Fluent HTTP)

1)利用Nuget界面管理器

html获取postNETC Fluent HTTP Flurl Get和Post要求应用办法及示例代码 Docker

干系文档:VS(Visual Studio)中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要求相应HttpResponseMessage

干系文档:HttpResponseMessage

var getResp = await "http://api.foo.com".GetAsync();var headResp = await "http://api.foo.com".HeadAsync();

3、获取要求JSON数据

从JSON API获取强类型的poco工具:

T poco = await "http://api.foo.com".GetJsonAsync();

当创建类来匹配JSON时,非通用版本返回一个dynamic:

dynamic d = await "http://api.foo.com".GetJsonAsync();

从一个返回JSON数组的API获取一个动态列表:

var list = await "http://api.foo.com".GetJsonListAsync();

4、获取要求strings, bytes, 和streams

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();

5、下载文件

// filename is optional here; it will default to the remote file namevar path = await "http://files.foo.com/image.jpg" .DownloadFileAsync("c:\\downloads", filename);

6、Post提交数据(JSON、Html Form)

POST提交JSON数据

await "http://api.foo.com".PostJsonAsync(new { a = 1, b = 2 });

仿照HTML表单post提交

await "http://site.com/login".PostUrlEncodedAsync(new { user = "user", pass = "pass"});

上述Post方法返回一个任务<HttpResponseMessage>。
当然,您可能希望在相应体中返回一些数据:

T poco = await url.PostJsonAsync(data).ReceiveJson<T>();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#标识符中不许可;下划线,正好相反)。

利用Basic authentication验证:

await url.WithBasicAuth("username", "password").GetJsonAsync();

OAuth 2.0 bearer token:

await url.WithOAuthBearerToken("mytoken").GetJsonAsync();

8、配置Fluent HTTP (Flurl)

设置超时(timeout)韶光

await url.WithTimeout(10).DownloadFileAsync(); // 10 secondsawait 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" System.Net.Http.HttpContent objectawait url.PostAsync(httpContent);// 利用HttpMethod指定要求办法await url.SendJsonAsync(HttpMethod.Options, poco);// 实行更繁芜配置的要求await url.SendAsync( HttpMethod.Trace, httpContent, // optional cancellationToken, // optional HttpCompletionOption.ResponseHeaderRead); // optional

干系文档:

https://flurl.dev/docs/fluent-http/.Net(C#)后台发送Get和Post要求的几种方法总结