RestSharp —(个人胡说八道🤣)
RestSharp
RestSharp是一个轻量的,不依赖任何第三方的模拟Http的组件或者类库。RestSharp具体以下特性;支持net4.0++,支持HTTP的GET, POST, PUT, HEAD, OPTIONS, DELETE等操作,支持oAuth 1, oAuth 2, Basic, NTLM and Parameter-based Authenticators等授权验证等。截止当前目前是github最高stars的http类库。
GitHub仓库
restsharp/RestSharp: Simple REST and HTTP API Client for .NET (github.com)
官方文档
RestSharp Next (v107) | RestSharp
使用介绍
NuGet包
请求类型
- Method.Get
- Method.Post
- Method.Put
- Method.Delete
- Method.Patch
- Method.Head
- Method.Options
- Method.Merge
- Method.Copy
- Method.Search
Http标头
AddObject
var obj = new {
status = 1,
priority = "high",
ids = new [] { "123", "456" }
};
request.AddObject(obj);
//或者 AddParameter(key, value);
request.AddParameter("status", 1);
request.AddParameter("priority", "high");
request.AddParameter("ids", "123,456");
AddUrlSegment
var request = new RestRequest("health/{entity}/status").AddUrlSegment("entity", "s2");
//请求地址会转换为 health/s2/status
AddStringBody
如果您有预序列化的有效负载(如 JSON 字符串),则可以使用它将其添加为正文参数。需要指定内容类型,以便远程终结点知道如何处理请求正文
var json = "{ data: { foo: \"bar\" } }";
request.AddStringBody(json, ContentType.Json);
JsonBody
- 指示 RestClient 在发出请求时将对象参数序列化为 JSON
- 将内容类型设置为
application/json
- 将请求正文的内部数据类型设置为
DataType.Json
不要将 JSON 字符串或某种实例发送到
var param = new MyClass { IntData = 1, StringData = "test123" };
request.AddJsonBody(param);
简单例子
private async Task<RestResponse> RestSharpTest(string requestUrl,Method apiMethod)
{
var client = new RestClient(requestUrl);
client.AcceptedContentTypes = new[] { "application/json", "text/json", "text/x-json", "text/javascript", "text/plain", "*/*" };
var request = new RestRequest();
switch (apiMethod)
{
case RequestTypeEnum.Get:
request = new RestRequest("", Method.Get);
break;
case RequestTypeEnum.Post:
request = new RestRequest("", Method.Post);
break;
case RequestTypeEnum.Put:
request = new RestRequest("", Method.Put);
break;
case RequestTypeEnum.Patch:
request = new RestRequest("", Method.Patch);
break;
case RequestTypeEnum.Delete:
request = new RestRequest("", Method.Delete);
break;
default:
break;
}
request.AddHeader("Content-Type", "application/json");
var response = await client.ExecuteAsync(request);
return response;
}