RestSharp RestSharp是一個輕量的,不依賴任何第三方的模擬Http的組件或者類庫。RestSharp具體以下特性;支持net4.0++,支持HTTP的GET, POST, PUT, HEAD, OPTIONS, DELETE等操作,支持oAuth 1, oAuth 2, Basic, ...
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;
}