using RestSharp; using RestSharp.Authenticators; using System; namespace EntrustSettle.Common.HttpRestSharp { /// /// Rest接口执行者 /// public class RestSharpClient : IRestSharp { /// /// 请求客户端 /// private RestClient client; /// /// 接口基地址 格式:http://apk.neters.club/ /// private string BaseUrl { get; set; } /// /// 默认的时间参数格式 /// private string DefaultDateParameterFormat { get; set; } /// /// 默认验证器 /// private IAuthenticator DefaultAuthenticator { get; set; } /// /// 构造函数 /// /// /// public RestSharpClient(string baseUrl, IAuthenticator authenticator = null) { BaseUrl = baseUrl; client = new RestClient(BaseUrl); DefaultAuthenticator = authenticator; //默认时间显示格式 DefaultDateParameterFormat = "yyyy-MM-dd HH:mm:ss"; //默认校验器 if (DefaultAuthenticator != null) { client.Authenticator = DefaultAuthenticator; } } /// /// 通用执行方法 /// /// 请求参数 /// /// 调用实例: /// var client = new RestSharpClient("http://apk.neters.club/"); /// var result = client.Execute(new RestRequest("v2/movie/in_theaters", Method.GET)); /// var content = result.Content;//返回的字符串数据 /// /// public IRestResponse Execute(IRestRequest request) { request.DateFormat = string.IsNullOrEmpty(request.DateFormat) ? DefaultDateParameterFormat : request.DateFormat; var response = client.Execute(request); return response; } /// /// 同步执行方法 /// /// 返回的泛型对象 /// 请求参数 /// /// var client = new RestSharpClient("http://apk.neters.club/"); /// var result = client.Execute>(new RestRequest("v2/movie/in_theaters", Method.GET)); /// /// public T Execute(IRestRequest request) where T : new() { request.DateFormat = string.IsNullOrEmpty(request.DateFormat) ? DefaultDateParameterFormat : request.DateFormat; var response = client.Execute(request); return response.Data; } /// /// 异步执行方法 /// /// 请求参数 /// 回调函数 /// /// 调用实例: /// var client = new RestSharpClient("http://apk.neters.club/"); /// client.ExecuteAsync>(new RestRequest("v2/movie/in_theaters", Method.GET), result => /// { /// var content = result.Content;//返回的字符串数据 /// }); /// /// [Obsolete] public RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action callback) { request.DateFormat = string.IsNullOrEmpty(request.DateFormat) ? DefaultDateParameterFormat : request.DateFormat; return client.ExecuteAsync(request, callback); } /// /// 异步执行方法 /// /// 返回的泛型对象 /// 请求参数 /// 回调函数 /// /// 调用实例: /// var client = new RestSharpClient("http://apk.neters.club/"); /// client.ExecuteAsync>(new RestRequest("v2/movie/in_theaters", Method.GET), result => /// { /// if (result.StatusCode != HttpStatusCode.OK) /// { /// return; /// } /// var data = result.Data;//返回数据 /// }); /// /// [Obsolete] public RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action> callback) where T : new() { request.DateFormat = string.IsNullOrEmpty(request.DateFormat) ? DefaultDateParameterFormat : request.DateFormat; return client.ExecuteAsync(request, callback); } } }