但是,如果先将其转成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) | RestSharphttps://restsharp.dev/v107/#restsharp-v107这里提到一个,生命周期的问题:
RestClient lifecycle
Do not instantiate
RestClient
for each HTTP call. RestSharp creates a new instance ofHttpClient
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;
- }
-
- }
-
-
- }