C# an open source cross-platform HTTP client library - RestSharp

1. Introduction to RestSharp

GitHub - restsharp/RestSharp: Simple REST and HTTP API Client for .NET Simple 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 interfaces perform CRUD operations; to connect to such Web Api interfaces and use them, you have various options; and one of the most popular is Amazon's RestSharp, mainly because of itssimplicity.

        RestSharp is an open-source, portable (cross-platform), lightweight .NET library primarily for consuming RESTful web services; it can perform CRUD (create, read, update, and delete) operations on data using any RESTful API; RestSharp is a popular library for interacting with RESTful APIs for making HTTP requests and parsing responses .

        Using RestSharp , you can interact with RESTful services while abstracting the technical details of HTTP requests. RestSharp provides a developer-friendly interface for interacting with RESTful services while abstracting the technical work of HTTP queries. RestSharp can handle both synchronous and asynchronous requests .

2. How to use RestSharp

2.1. Install the Nuget package of RestSharp

2.2. Basic usage of RestSharp

   ① Instantiate the RestSharp client

var client = new RestClient("http://192.168.3.10:8085/api");

    ② Instantiate a request (including requested resources, parameters of resource requests)

var request = new RestRequest("GetArea");
            request.Method = Method.Post;

    ③ Execution request

var reponse = await client.ExecutePostAsync(request);

2.3. Example of using RestSharp

        For example, I have a WebApi interface [ http://192.168.3.10:8085/api/GetArea ] to obtain area information, which is a Post type; an example of using RestSharp to obtain corresponding information is as follows:

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;
        }


 
        #endregion


        public 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;
            }

        }
    }

The execution results are as follows:

3. Reference materials 

RestSharp Next (v107+) | RestSharpicon-default.png?t=N5K3https://restsharp.dev/v107/#restsharp-v107How to consume a Web API using RestSharp | InfoWorldicon-default.png?t=N5K3https://www.infoworld.com/article/3252769/how-to-consume-a-web-api-using-restsharp.html How To Consume a WebAPI with RestSharp -- Visual Studio Magazineicon-default.png?t=N5K3https://visualstudiomagazine.com/articles/2015/10/01/consume-a-webapi.aspx

Consume a RESTful API Using RestSharp and C# - Devart Blogicon-default.png?t=N5K3https://blog.devart.com/consume-a-restful-api-using-restsharp-and-c.html

Guess you like

Origin blog.csdn.net/xiaochenXIHUA/article/details/131544292
Recommended