【C#】RestSharp踩坑日记

踩坑记录

一  返回值无法显示中文的问题:

 但是,如果先将其转成json,再将其转成字符串,就能显示中文了。

Newtonsoft.Json.Linq.JObject jo = Newtonsoft.Json.Linq.JObject.Parse(response.Content);

jo.ToString();

全网都没找到靠谱的,这个是最简单的方式。 

 

二  报错信息:无法发送具有此谓词类型的内容正文

 这个其实就是Get的时候,不应该添加这个,AddHeader("Content-Type", $"{content_type}; charset=UTF-8"),这个是Post才会用到的。

代码封装

RestSharp之前一直使用的是老版本的,直接添加的dll,其实RestSharp一直再更新换代,使用Nuget可以安装最新的版本。

 我们可以通过它的官方文档,查看它的使用方式:

RestSharp Next (v107) | RestSharpicon-default.png?t=M85Bhttps://restsharp.dev/v107/#restsharp-v107这里提到一个,生命周期的问题:

RestClient lifecycle

Do not instantiate RestClient for each HTTP call. RestSharp creates a new instance of HttpClient internally, and you will get lots of hanging connections, and eventually exhaust the connection pool.

If you use a dependency-injection container, register your API client as a singleton.

就是说,不要每次调用的时候都创建一个client,这样会耗尽连接池。

好了,上代码:

internal class RestSharpRequestHandler
    {
        private RestClient client;
        private RestRequest request;

        public RestSharpRequestHandler()
        {
            var options = new RestClientOptions()
            {
                ThrowOnAnyError = true,  //设置不然不会报异常
                MaxTimeout = 1000
            };
            client = new RestClient(options);
        }


        public string Post(string url, string str, string content_type = "application/json; charset=UTF-8")
        {
            try
            {

                this.request = new RestRequest(url)
                    .AddHeader("Content-Type", $"{content_type}; charset=UTF-8")
                    .AddStringBody(str,DataFormat.Json);

                var response = client.Post(request);
                Newtonsoft.Json.Linq.JObject jo = Newtonsoft.Json.Linq.JObject.Parse(response.Content);


                return jo.ToString();
            }
            catch (Exception ex)
            {

                return "连接服务器出错:\r\n" + ex.Message;
            }

        }

        public string Get(string url, string content_type = "application/json; charset=UTF-8")
        {
            try
            {
                request = new RestRequest(url);
                var response = client.Get(request);
                JObject jo = JObject.Parse(response.Content);
                return jo.ToString();
            }
            catch (Exception ex)
            {
                return "连接服务器出错:\r\n" + ex.Message;
            }

        }


    }

posted @ 2022-09-08 14:25  宋桓公  阅读(621)  评论(0编辑  收藏  举报