我用的版本:
简单封装一下:
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
internal class RestSharpRequestHandler
{
private RestClient client;
private RestRequest request;
public int timeout=30 * 1000; //默认设置超时30s
public string Post(string url, string str, string content_type= "application/json; charset=UTF-8")
{
try
{
this.client = new RestClient(url);
client.Timeout = timeout;
client.ThrowOnAnyError = true; //设置不然不会报异常
this.request = new RestRequest();
request.Method = Method.POST;
request.AddHeader("Content-Type", $"{content_type}; charset=UTF-8");
request.AddJsonBody(str);
IRestResponse response = client.Execute(request);
var content = response.Content;
return content;
}
catch (Exception ex)
{
return "连接服务器出错:\r\n" + ex.Message;
}
}
public string Get(string url, string content_type = "application/json; charset=UTF-8")
{
try
{
this.client = new RestClient(url);
client.Timeout = timeout;
client.ThrowOnAnyError = true; //设置不然不会报异常
this.request = new RestRequest();
request.Method = Method.GET;
request.AddHeader("Content-Type", $"{content_type}; charset=UTF-8");
IRestResponse response = client.Execute(request);
var content = response.Content;
return content;
}
catch (Exception ex)
{
return "连接服务器出错:\r\n" + ex.Message;
}
}
}
这里对Get和Post进行了简单的封装。
对于超时我这里解释一下:
client.Timeout = timeout;
client.ThrowOnAnyError = true; //设置不然不会报异常
首先是对RestClient的对象设置Timeout,
其次将ThrowOnAnyError设置为true,不然是捕获不到任何异常的!
版权声明:本文为songhuangong123原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。