.NET(C#) Fluent HTTP (Flurl Get和Post请求)使用方法及示例代码

-
本文主要介绍Fluent HTTP (Flurl)的使用,包括执行Get和Post等请求操作, Flurl允许您直接从连贯URL构建器链执行许多常见的HTTP任务。其下是HttpClient和相关类。正如您将看到的,Flurl使用方便的方法和流畅的优点增强了HttpClient,但并没有试图完全抽象它。


1、命名空间

 Flurl;
 Flurl.Http;

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

1)使用Nuget界面管理器

相关文档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

 getResp =  ;
 headResp =  ;

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获取一个动态列表:

 list =  .GetJsonListAsync();

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

 text =  .GetStringAsync();[] bytes =  .GetBytesAsync();
Stream stream =  .GetStreamAsync();

5、下载文件

 path =  
    .DownloadFileAsync(, filename);

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

POST提交JSON数据

 .PostJsonAsync( { a = , b =  });

模拟HTML表单post提交

 .PostUrlEncodedAsync( { 
    user = , 
    pass = });

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

T poco =  url.PostJsonAsync(data).ReceiveJson<T>(); d =  url.PostUrlEncodedAsync(data).ReceiveJson(); s =  url.PostUrlEncodedAsync(data).ReceiveString();

7、配置http请求头(header)

 url.WithHeader(, ).GetJsonAsync(); url.WithHeaders( { Accept = , User_Agent =  }).GetJsonAsync();

在上面的第二个示例中,User_Agent将自动呈现为User-Agent标题名称。(连字符在标头名称中非常常见,但在C#标识符中不允许;下划线,恰恰相反)。

使用Basic authentication验证

 url.WithBasicAuth(, ).GetJsonAsync();

OAuth 2.0 bearer token:


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


8、配置Fluent HTTP (Flurl)

设置超时(timeout)时间

 url.WithTimeout().DownloadFileAsync();  url.WithTimeout(TimeSpan.FromMinutes()).DownloadFileAsync();

设置cookies

 url.WithCookie(, , expDate).HeadAsync(); url.WithCookies( { c1 = , c2 =  }, expDate).HeadAsync();

取消请求

 cts =  CancellationTokenSource(); 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

阅读次数:

相关文章!