.NET Core(C#)使用RestSharp可以实现一些后台Http请求相关操作,本文主要介绍通过RestSharp执行GET和POST请求,在下载很大文件时需要大量内存时通过文件流优化,以请求时自动管理cookie。

1、使用Nuget安装引用RestSharp

1)使用Nuget界面管理器

相关文档VS(Visual Studio)中Nuget的使用

2)使用Package Manager命令安装

PM> Install-Package RestSharp -Version 106.6.10

3)使用.NET CLI命令安装

> dotnet add package RestSharp --version 106.6.10

4) 支持的平台

.NET Framework 4.5.2
.NET Standard 2.0
Windows 可使用 .NET Framework
Windows 可使用 .NET Core
Linux 或 Mac 可使用 Mono
Linux 或 Mac 可使用 .NET Core

2、RestSharp执行GET和POST请求

RestSharp包括用于基本HTTP(Authorization header),NTLM和基于参数的系统的身份验证器。您可以通过实现IAuthenticator并将其注册到RestClient来编写自己的实现:

using RestSharp;
using RestSharp.Authenticators;
var client = new RestClient("https://api.twitter.com/1.1");
client.Authenticator = new HttpBasicAuthenticator("username", "password");
var request = new RestRequest("statuses/home_timeline.json", DataFormat.Json);
var response = client.Get(request);
//get请求
var client = new RestClient("http://example.com");
client.Authenticator = new SimpleAuthenticator("username", "foo", "password", "bar");
var request = new RestRequest("resource", Method.GET);
client.Execute(request);
//post请求
var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource
// easily add HTTP Headers
request.AddHeader("header", "value");
// add files to upload (works with compatible verbs)
request.AddFile(path);
// 执行请求
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
// 或自动反序列化结果
// return content type is sniffed but can be explicitly set via RestClient.AddHandler();
RestResponse<Person> response2 = client.Execute<Person>(request);
var name = response2.Data.Name;
// 简单的异步支持
client.ExecuteAsync(request, response => {
    Console.WriteLine(response.Content);
});
// 异步与反序列化
var asyncHandle = client.ExecuteAsync<Person>(request, response => {
    Console.WriteLine(response.Data.Name);
});
// 根据需要中止请求
asyncHandle.Abort();

3、下载大文件

使用Stream来避免请求内容的内存缓冲。在检索将立即写入磁盘的大量数据时很有用。

string tempFile = Path.GetTempFileName();
using (var writer = File.OpenWrite(tempFile))
{
    var client = new RestClient(baseUrl);
    var request = new RestRequest("Assets/LargeFile.7z");
    request.ResponseWriter = responseStream =>
    {
        using (responseStream)
        {
            responseStream.CopyTo(writer);
        }
    };
    var response = client.DownloadData(request);
}

4、自动Cookie管理

RestSharp 102.4+支持System.Net.CookieContainer对任何IRestClient实例的所有请求使用共享。这样,在响应中设置或未设置的任何cookie都将在后续请求中使用。为了使用shared CookieContainer,只需RestClient在使用实例之前在实例上设置属性:

var client = new RestClient("http://server/");
client.CookieContainer = new System.Net.CookieContainer();

相关文档

https://github.com/restsharp/RestSharp

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

.Net(C#) 后台使用WebClient(客户端控制台程序)执行Get和Post请求的方法

.Net(C#)后台发送Get和Post请求的几种方法总结

推荐文档