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请求)使用方法及示例代码