一、RestSharp简介
GitHub - restsharp/RestSharp: Simple REST and HTTP API Client for .NETSimple REST and HTTP API Client for .NET. Contribute to restsharp/RestSharp development by creating an account on GitHub.https://github.com/restsharp/RestSharp 在进行软件开发的时侯,你可能经常需要使用一些公共的Web Api接口执行 CRUD 操作;要连接到这样的Web Api接口并使用它们,您可以有多样的选择;而其中最流行的便是亚马孙的RestSharp,主要是因为它的简单性。
RestSharp 是一个开源的、可移植(跨平台)、轻量级的.NET 库,主要用于使用 RESTful Web 服务;它可以使用任何 RESTful API 对数据执行 CRUD (创建、读取、更新和删除)操作;RestSharp 是一个用于与 RESTful API 交互的流行库,用于发出 HTTP 请求和解析响应。
使用 RestSharp,您可以在抽象 HTTP 请求的技术细节时与 RESTful 服务进行交互。RestSharp 提供了一个开发人员友好的界面,用于在抽象 HTTP 查询的技术工作时与 RESTful 服务进行交互。RestSharp 可以处理同步和异步请求。
二、RestSharp使用方法
2.1、安装RestSharp的Nuget包
2.2、RestSharp的基础使用方法
①实例化RestSharp客户端
var client = new RestClient("http://192.168.3.10:8085/api");
②实例化一个请求(包含请求的资源、资源请求的参数)
var request = new RestRequest("GetArea");request.Method = Method.Post;
③执行请求
var reponse = await client.ExecutePostAsync(request);
2.3、RestSharp的使用示例
比如我这里有一个WebApi接口【http://192.168.3.10:8085/api/GetArea】用于获取区域信息,是Post类型;使用RestSharp获取相应信息的示例如下:
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;class Program{static void Main(string[] args){Console.WriteLine("Hello World!");Task<RestResponse> testResult = Test1();Console.WriteLine($"Main方法:{testResult.GetAwaiter().GetResult().Content}\n\n");ResultDTO resultDTO = JsonConvert.DeserializeObject<ResultDTO>(testResult.GetAwaiter().GetResult().Content);Console.WriteLine($"Test1方法:{resultDTO}\n");//Test11();Console.ReadLine();}//多线程测试private static void Test11(){for (int i = 0; i < 3; i++){ThreadPool.QueueUserWorkItem(new WaitCallback((obj) =>{Console.WriteLine($"{DateTime.Now} 启动{obj} 线程");Task<RestResponse> testResult3 = Test1("http://192.168.3.10:8085/api/", "GetUsers", "{ \"UserName\":\"\"}");}),i);}}/// <summary>/// 测试/// </summary>/// <param name="baseUrl">WebApi的基础路径</param>/// <param name="resourceName">WebApi的资源名称</param>/// <param name="jsonPara">WebApi资源的json参数字符串</param>/// <returns></returns>public static async Task<RestResponse> Test1(string baseUrl= "http://192.168.3.10:8085/api/",string resourceName= "GetArea", string jsonPara=null){if (string.IsNullOrEmpty(baseUrl) ||string.IsNullOrEmpty(resourceName)) return null;var client = new RestClient(baseUrl);var request = new RestRequest(resourceName);request.Method = Method.Post;if (!string.IsNullOrEmpty(jsonPara)){request.AddBody(jsonPara);}//var reponse = await client.ExecutePostAsync(request);//ResultDTO resultDTO = JsonConvert.DeserializeObject<ResultDTO>(reponse.Content);//Console.WriteLine($"Test1方法:{resultDTO}\n");var reponse = await client.ExecutePostAsync<ResultDTO>(request);return reponse;}/// <summary>/// 解析Json字符串(首尾没有中括号)【线程安全】/// </summary>/// <param name="jsonStr">需要解析的Json字符串</param>/// <returns>返回解析好的Hashtable表</returns>private static Hashtable AnalayJsonString(string jsonStr){Hashtable ht = new Hashtable();if (!string.IsNullOrEmpty(jsonStr)){JObject jo = (JObject)JsonConvert.DeserializeObject(jsonStr);foreach (var item in jo){ht.Add(item.Key, item.Value);}}foreach (DictionaryEntry item in ht){Console.WriteLine(item.Key + " " + item.Value);}return ht;}#region 解析Json字符串(首尾有中括号)/// <summary>/// 解析Json字符串(首尾有中括号[存在相同键])【线程安全】/// </summary>/// <param name="jsonStr">需要解析的Json字符串</param>/// <returns>返回解析好的数据</returns>public static ConcurrentBag<KeyValuePair<string, object>> AnalayJsonStringMiddleBrackets(string jsonStr){ConcurrentBag<KeyValuePair<string, object>> cb = new ConcurrentBag<KeyValuePair<string, object>>();if (!string.IsNullOrEmpty(jsonStr)){JArray jArray = (JArray)JsonConvert.DeserializeObject(jsonStr);//jsonArrayText必须是带[]字符串数组if (jArray != null && jArray.Count > 0){foreach (var item in jArray){foreach (JToken jToken in item){string[] strTmp = jToken.ToString().Split(':');KeyValuePair<string, object> kv = new KeyValuePair<string, object>(strTmp[0].Replace("\"", ""), strTmp[1].Replace("\"", ""));cb.Add(kv);}}}foreach (var item in cb){Console.WriteLine(item.Key + " " + item.Value);}}return cb;}#endregionpublic class ResultDTO{public string Success { get; set; }public string Result { get; set; }public string StatusCode { get; set; }public string Message { get; set; }public override string ToString(){string tmp = string.Empty;if (Result.Contains('[')){tmp = $"\nSuccess:{Success}\nStatusCode:{StatusCode}\nMessage:{Message}\nResult:{AnalayJsonStringMiddleBrackets(Result)}\n";}else{tmp = $"\nSuccess:{Success}\nStatusCode:{StatusCode}\nMessage:{Message}\nResult:{AnalayJsonString(Result)}\n";}return tmp;}}}
执行结果如下:
三、参考资料
RestSharp Next (v107+) | RestSharphttps://restsharp.dev/v107/#restsharp-v107How to consume a Web API using RestSharp | InfoWorld
https://www.infoworld.com/article/3252769/how-to-consume-a-web-api-using-restsharp.html How To Consume a WebAPI with RestSharp -- Visual Studio Magazine
https://visualstudiomagazine.com/articles/2015/10/01/consume-a-webapi.aspx
Consume a RESTful API Using RestSharp and C# - Devart Bloghttps://blog.devart.com/consume-a-restful-api-using-restsharp-and-c.html