/// <summary> /// Ejecuta la llamada al servicio REST con RestSharp /// </summary> /// <typeparam name="T">Tipo de dato del objeto de retorno</typeparam> /// <param name="uri">url del endpoint del servicio rest</param> /// <param name="httpMethod">Método HTTP</param> /// <param name="objJsonBody">Objeto request body</param> /// <returns>Interface IRestResponse<T></returns> public static RestSharp.IRestResponse<T> Execute<T>(string uri, RestSharp.Method httpMethod, object objJsonBody = null, string authorizationHeader = null) where T : new() { var client = new RestSharp.RestClient(uri); var request = new RestSharp.RestRequest(httpMethod); request.AddHeader("cache-control", "no-cache"); request.AddHeader("Content-Type", "application/json"); if (!string.IsNullOrEmpty(authorizationHeader)) { request.AddHeader("Authorization", authorizationHeader); } if (objJsonBody != null) request.AddParameter("application/json", objJsonBody, RestSharp.ParameterType.RequestBody); //request.AddJsonBody(objJsonBody); System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; RestSharp.IRestResponse<T> response = null; for (int i = 0; i < 2; i++) { response = client.Execute<T>(request); if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created) break; else if (response.StatusCode == HttpStatusCode.RequestTimeout || (int)response.StatusCode > 500) Thread.Sleep(int.Parse(ConfigurationManager.AppSettings["timer_web_api"])); } return response; }
/// <summary> /// this class models a request that can be sent to a service /// </summary> /// <param name="headers">the headers that should be sent as part of the request</param> /// <param name="httpMethod">the httpMethod of the request</param> /// <param name="pathParameters">any path parameters required</param> /// <param name="queryParameters">any query parameters required</param> /// <param name="requestBody">a request body if required</param> public Request(RESTHeaders headers, RestSharp.Method httpMethod, PathParams pathParameters, IQueryParams queryParameters, IRequestBody requestBody) { this.headers = headers; this.httpMethod = httpMethod; this.pathParameters = pathParameters; this.queryParameters = queryParameters; this.requestBody = requestBody; }
public RestSharp.RestRequest CreateRequest(string resource, RestSharp.Method method) { var request = new RestSharp.RestRequest(resource, method); request.RequestFormat = RestSharp.DataFormat.Json; request.XmlSerializer.DateFormat = "yyyy-MM-ddTHH:mm:ss.fff"; request.JsonSerializer.DateFormat = "yyyy-MM-ddTHH:mm:ss.fff"; request.AddHeader("apikey", GlobalConfiguration.Configuration.ApiKey); request.AddHeader("Accept", "application/json, text/json, text/x-json"); request.Timeout = 1000 * 30; return(request); }
public string ServisIslem(string url, string istekler, bool isLogin = false, string Method = "POST", string ContentType = "application/json") { RestSharp.Method GelenMethod = RestSharp.Method.POST; switch (Method) { case "POST": GelenMethod = RestSharp.Method.POST; break; case "PUT": GelenMethod = RestSharp.Method.PUT; break; case "DELETE": GelenMethod = RestSharp.Method.DELETE; break; default: break; } var client = new RestSharp.RestClient(kokurl + url); client.Timeout = -1; var request = new RestSharp.RestRequest(GelenMethod); request.AddHeader("Content-Type", ContentType); if (!isLogin) { request.AddHeader("Authorization", "Bearer " + GetApiToken()); } request.AddParameter(ContentType, istekler, RestSharp.ParameterType.RequestBody); RestSharp.IRestResponse response = client.Execute(request); if (response.StatusCode != HttpStatusCode.Unauthorized && response.StatusCode != HttpStatusCode.InternalServerError && response.StatusCode != HttpStatusCode.BadRequest && response.StatusCode != HttpStatusCode.Forbidden && response.StatusCode != HttpStatusCode.MethodNotAllowed && response.StatusCode != HttpStatusCode.NotAcceptable && response.StatusCode != HttpStatusCode.RequestTimeout && response.StatusCode != HttpStatusCode.NotFound) { return(response.Content); } else { return("Hata"); } }
/// <summary> /// 通过安全代理调用目标uri /// </summary> /// <param name="serverUrl">安全代理服务端地址</param> /// <param name="body">代理请求体内容,不支持文件</param> /// <param name="contentType">代理请求 contentType</param> /// <param name="targetUrl">代理调用调至</param> /// <param name="serverPublicKey">服务端公钥</param> /// <param name="clientPublicKey">本地公钥</param> /// <param name="clientPrivateKey">本地私钥</param> /// <param name="encoding">编码方式</param> /// <param name="method"></param> /// <param name="queryStrings"></param> /// <param name="headers"></param> /// <param name="cookies"></param> /// <param name="timeout"></param> /// <returns></returns> public static async Task <string> Invoke( string serverUrl, string body, string contentType, string targetUrl, string serverPublicKey, string clientPublicKey, string clientPrivateKey, string encoding = "UTF-8", RestSharp.Method method = RestSharp.Method.POST, IEnumerable <KeyValuePair <string, string> > queryStrings = null, IDictionary <string, string> headers = null, IDictionary <string, string> cookies = null, int timeout = 60 ) { var enc = Encoding.GetEncoding(encoding); if (string.IsNullOrWhiteSpace(body)) { body = "empty"; } var encoded = SecretHelper.Encrypt(body, serverPublicKey, enc); var signature = SecretHelper.Sign(body, clientPrivateKey, enc); var request = new RequestObj { Body = encoded, Signature = signature, ContentType = contentType, TargetUrl = targetUrl, Encode = encoding, QueryStrings = queryStrings, Cookies = cookies, Headers = headers, Method = method, Timeout = timeout }; var resObj = await HttpHelper.PostJson <ResponseObj>(serverUrl, request, timeout : 120); var resStr = SecretHelper.Decrypt(resObj.Body, clientPrivateKey, enc); if (!SecretHelper.Verify(resStr, resObj.Signature, serverPublicKey, enc)) { throw new Exception("安全代理调用结果签名验证错误"); } return(resStr == "empty" ? "" : resStr); }
public static RestSharp.IRestResponse <T> Execute <T>(string uri, RestSharp.Method method, object objJsonBody = null) where T : new() { var client = new RestSharp.RestClient(uri); var request = new RestSharp.RestRequest(method); request.AddHeader("cache-control", "no-cache"); request.AddHeader("Content-Type", "application/json"); if (objJsonBody != null) { request.AddJsonBody(objJsonBody); } RestSharp.IRestResponse <T> response = client.Execute <T>(request); return(response); }
/// <summary> /// Makes the HTTP request (Sync). /// </summary> /// <param name="path">URL path.</param> /// <param name="method">HTTP method.</param> /// <param name="queryParams">Query parameters.</param> /// <param name="postBody">HTTP body (POST request).</param> /// <param name="headerParams">Header parameters.</param> /// <param name="formParams">Form parameters.</param> /// <param name="fileParams">File parameters.</param> /// <param name="authSettings">Authentication settings.</param> /// <returns>Object</returns> public Object CallApi(String path, RestSharp.Method method, Dictionary <String, String> queryParams, String postBody, Dictionary <String, String> headerParams, Dictionary <String, String> formParams, Dictionary <String, FileParameter> fileParams, String[] authSettings) { var request = new RestRequest(path, method); UpdateParamsForAuth(queryParams, headerParams, authSettings); // add default header, if any foreach (var defaultHeader in _defaultHeaderMap) { request.AddHeader(defaultHeader.Key, defaultHeader.Value); } // add header parameter, if any foreach (var param in headerParams) { request.AddHeader(param.Key, param.Value); } // add query parameter, if any foreach (var param in queryParams) { request.AddParameter(param.Key, param.Value, ParameterType.GetOrPost); } // add form parameter, if any foreach (var param in formParams) { request.AddParameter(param.Key, param.Value, ParameterType.GetOrPost); } // add file parameter, if any foreach (var param in fileParams) { request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType); } if (postBody != null) // http body (model) parameter { request.AddParameter("application/json", postBody, ParameterType.RequestBody); } return((Object)RestClient.Execute(request)); }
/// <summary> /// Exectute a REST Request /// </summary> /// <param name="path">Api path</param> /// <param name="method">Request Method</param> /// <param name="token">Optional: Token</param> /// <param name="body">Optional: Body object</param> /// <returns>Json Dictionary</returns> public SimpleJson.JsonObject ExecuteRequest(string path, RestSharp.Method method, object body = null) { try { string restpath = (path.StartsWith(BaseUri)) ? path : String.Format("{0}{1}", BaseUri, path); var request = new RestSharp.RestRequest(restpath, method); request.AddHeader("X-TP-APPLICATION-CODE", AppKey); request.AddHeader("Content-Type", "application/json"); if (this.Token != string.Empty) { request.AddHeader("Authorization", String.Format("Bearer {0}", this.Token)); } request.RequestFormat = RestSharp.DataFormat.Json; if (body != null) { request.AddBody(body); } request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; }; var response = RClient.Execute(request); return(SimpleJson.SimpleJson.DeserializeObject(response.Content) as SimpleJson.JsonObject); } catch (Exception e) { throw e; } }
public BatchableOperation(RestSharp.Method method, string path, string bodyJson) { this.Method = method; this.Path = path; this.BodyJson = bodyJson; }
public RestRequest(object pOST, RestSharp.Method gET) { this.pOST = pOST; }
public RestRequestInfo(RestSharp.Method method, string root) { Method = method; Root = root; }
public ILicenseResponse PerformAction(Consts.Action action, License license, RestSharp.Method httpMethod = RestSharp.Method.GET) { if (license == null) { throw new ArgumentNullException("license"); } if (action == Consts.Action.Unknown) { throw new ArgumentNullException("action"); } if (Configuration == null) { throw new NullReferenceException("Configuration property is null."); } if (string.IsNullOrWhiteSpace(Configuration.PostURL)) { throw new NullReferenceException("The PostURL of the specified configuration object is white space or null."); } if (action == Consts.Action.Create) { if (string.IsNullOrWhiteSpace(Configuration.SecretKey)) { throw new NullReferenceException("The SecretKey of the specified configuration object is an empty string or null."); } } if (action != Consts.Action.Create) { if (string.IsNullOrWhiteSpace(Configuration.ActivationKey)) { throw new NullReferenceException("the ActivationKey of the specified configuration object is white space or null."); } } var restClient = new RestSharp.RestClient(Configuration.PostURL); var restRequest = new RestSharp.RestRequest(); restRequest.Method = httpMethod; restRequest.AddHeader("Content-Type", "application/x-www-form-urlencoded"); if (action == Consts.Action.Unknown) { throw new UndefinedActionException("Undefined action."); } else { string description = Helper.DescriptionAttr <Consts.Action>(action); restRequest.AddParameter("slm_action", description); } switch (action) { case WordPressLicenseManagerNETClient.Consts.Action.Unknown: break; case WordPressLicenseManagerNETClient.Consts.Action.Activate: restRequest.AddParameter("secret_key", Configuration.ActivationKey); // add first name if (string.IsNullOrWhiteSpace(license.FirstName) == false) { restRequest.AddParameter("first_name", license.FirstName); } // add domain restRequest.AddParameter("registered_domain", license.RegisteredDomain); // add first name if (string.IsNullOrWhiteSpace(license.FirstName) == false) { restRequest.AddParameter("first_name", license.FirstName); } // add last name if (string.IsNullOrWhiteSpace(license.LastName) == false) { restRequest.AddParameter("last_name", license.LastName); } // add company name if (string.IsNullOrWhiteSpace(license.CompanyName) == false) { restRequest.AddParameter("company_name", license.CompanyName); } // add email if (string.IsNullOrWhiteSpace(license.Email) == false) { restRequest.AddParameter("email", license.Email); } if (string.IsNullOrWhiteSpace(license.Key) == false) { restRequest.AddParameter("license_key", license.Key); } break; case WordPressLicenseManagerNETClient.Consts.Action.Deactivate: restRequest.AddParameter("secret_key", Configuration.ActivationKey); // add first name if (string.IsNullOrWhiteSpace(license.FirstName) == false) { restRequest.AddParameter("first_name", license.FirstName); } // add domain restRequest.AddParameter("registered_domain", license.RegisteredDomain); // add first name if (string.IsNullOrWhiteSpace(license.FirstName) == false) { restRequest.AddParameter("first_name", license.FirstName); } // add last name if (string.IsNullOrWhiteSpace(license.LastName) == false) { restRequest.AddParameter("last_name", license.LastName); } // add company name if (string.IsNullOrWhiteSpace(license.CompanyName) == false) { restRequest.AddParameter("company_name", license.CompanyName); } // add email if (string.IsNullOrWhiteSpace(license.Email) == false) { restRequest.AddParameter("email", license.Email); } if (string.IsNullOrWhiteSpace(license.Key) == false) { restRequest.AddParameter("license_key", license.Key); } break; case WordPressLicenseManagerNETClient.Consts.Action.Check: restRequest.AddParameter("secret_key", Configuration.ActivationKey); // add first name if (string.IsNullOrWhiteSpace(license.FirstName) == false) { restRequest.AddParameter("first_name", license.FirstName); } // add last name if (string.IsNullOrWhiteSpace(license.LastName) == false) { restRequest.AddParameter("last_name", license.LastName); } // add company name if (string.IsNullOrWhiteSpace(license.CompanyName) == false) { restRequest.AddParameter("company_name", license.CompanyName); } // add email if (string.IsNullOrWhiteSpace(license.Email) == false) { restRequest.AddParameter("email", license.Email); } if (string.IsNullOrWhiteSpace(license.Key) == false) { restRequest.AddParameter("license_key", license.Key); } break; case WordPressLicenseManagerNETClient.Consts.Action.Get: restRequest.AddParameter("secret_key", Configuration.ActivationKey); // add first name if (string.IsNullOrWhiteSpace(license.FirstName) == false) { restRequest.AddParameter("first_name", license.FirstName); } // add last name if (string.IsNullOrWhiteSpace(license.LastName) == false) { restRequest.AddParameter("last_name", license.LastName); } // add company name if (string.IsNullOrWhiteSpace(license.CompanyName) == false) { restRequest.AddParameter("company_name", license.CompanyName); } // add email if (string.IsNullOrWhiteSpace(license.Email) == false) { restRequest.AddParameter("email", license.Email); } if (string.IsNullOrWhiteSpace(license.Key) == false) { restRequest.AddParameter("license_key", license.Key); } if (string.IsNullOrWhiteSpace(license.ProductReference) == false) { restRequest.AddParameter("product_ref", license.ProductReference); } break; case WordPressLicenseManagerNETClient.Consts.Action.Create: restRequest.AddParameter("secret_key", Configuration.SecretKey); restRequest.AddParameter("date_created", license.DateCreated.ToString("yyyy-MM-dd")); restRequest.AddParameter("date_renewed", license.DateRenewed.ToString("yyyy-MM-dd")); restRequest.AddParameter("date_expiry", license.DateExpired.ToString("yyyy-MM-dd")); // add license ID : update if provided, if not : create if (!string.IsNullOrWhiteSpace(license.Id)) { restRequest.AddParameter("id", license.Id); } // add product name if (string.IsNullOrWhiteSpace(license.ProductReference) == false) { restRequest.AddParameter("product_ref", license.ProductReference); } // add subscriber id if (string.IsNullOrWhiteSpace(license.SubscriberID) == false) { restRequest.AddParameter("subscr_id", license.SubscriberID); } // add mode if (string.IsNullOrWhiteSpace(license.Mode) == false) { restRequest.AddParameter("lic_mode", license.Mode); } // add software version if (string.IsNullOrWhiteSpace(license.Version) == false) { restRequest.AddParameter("version", license.Version); } // add ip address if (string.IsNullOrWhiteSpace(license.IpAddress) == false) { restRequest.AddParameter("ip_address", license.IpAddress); } // add registered domain if (string.IsNullOrWhiteSpace(license.RegisteredDomain) == false) { restRequest.AddParameter("registered_domain", license.RegisteredDomain); } // add first name if (string.IsNullOrWhiteSpace(license.FirstName) == false) { restRequest.AddParameter("first_name", license.FirstName); } // add last name if (string.IsNullOrWhiteSpace(license.LastName) == false) { restRequest.AddParameter("last_name", license.LastName); } // add company name if (string.IsNullOrWhiteSpace(license.CompanyName) == false) { restRequest.AddParameter("company_name", license.CompanyName); } // add email if (string.IsNullOrWhiteSpace(license.Email) == false) { restRequest.AddParameter("email", license.Email); } // add maximum number of domains allowed if (license.MaximumDomainAllowed >= 0) { restRequest.AddParameter("maximum_domained_allowed", license.MaximumDomainAllowed); } // add license key if (string.IsNullOrWhiteSpace(license.Key) == false) { restRequest.AddParameter("license_key", license.Key); } else { throw new NewLicenseEmptyKeyException("Cannot create license with empty key."); } break; case WordPressLicenseManagerNETClient.Consts.Action.Update: restRequest.AddParameter("secret_key", Configuration.SecretKey); restRequest.AddParameter("date_created", license.DateCreated.ToString("yyyy-MM-dd")); restRequest.AddParameter("date_renewed", license.DateRenewed.ToString("yyyy-MM-dd")); restRequest.AddParameter("date_expiry", license.DateExpired.ToString("yyyy-MM-dd")); // add license ID if (!string.IsNullOrWhiteSpace(license.Id)) { restRequest.AddParameter("id", license.Id); } // add product name if (string.IsNullOrWhiteSpace(license.ProductReference) == false) { restRequest.AddParameter("product_ref", license.ProductReference); } // add subscriber id if (string.IsNullOrWhiteSpace(license.SubscriberID) == false) { restRequest.AddParameter("subscr_id", license.SubscriberID); } // add mode if (string.IsNullOrWhiteSpace(license.Mode) == false) { restRequest.AddParameter("lic_mode", license.Mode); } // add software version if (string.IsNullOrWhiteSpace(license.Version) == false) { restRequest.AddParameter("version", license.Version); } // add ip address if (string.IsNullOrWhiteSpace(license.IpAddress) == false) { restRequest.AddParameter("ip_address", license.IpAddress); } // add registered domain if (string.IsNullOrWhiteSpace(license.RegisteredDomain) == false) { restRequest.AddParameter("registered_domain", license.RegisteredDomain); } // add first name if (string.IsNullOrWhiteSpace(license.FirstName) == false) { restRequest.AddParameter("first_name", license.FirstName); } // add last name if (string.IsNullOrWhiteSpace(license.LastName) == false) { restRequest.AddParameter("last_name", license.LastName); } // add company name if (string.IsNullOrWhiteSpace(license.CompanyName) == false) { restRequest.AddParameter("company_name", license.CompanyName); } // add email if (string.IsNullOrWhiteSpace(license.Email) == false) { restRequest.AddParameter("email", license.Email); } // add maximum number of domains allowed if (license.MaximumDomainAllowed >= 0) { restRequest.AddParameter("maximum_domained_allowed", license.MaximumDomainAllowed); } // add license key if (string.IsNullOrWhiteSpace(license.Key) == false) { restRequest.AddParameter("license_key", license.Key); } break; default: break; } var response = restClient.Execute(restRequest); var content = response.Content; var rootObject = new LicenseResponse(); if (response.StatusCode == HttpStatusCode.OK) { var responseRet = response.Content; // deserialize response var settings = new JsonSerializerSettings(); settings.MissingMemberHandling = MissingMemberHandling.Ignore; var format = "dd-MM-yyyy"; var dateTimeConverter = new IsoDateTimeConverter { DateTimeFormat = format }; var converters = new List <JsonConverter>(); converters.Add(new AbstractConverter <LicenseResponse, ILicenseResponse>()); converters.Add(dateTimeConverter); settings.Converters = converters; var ret = JsonConvert.DeserializeObject(content, typeof(ILicenseResponse), settings) as ILicenseResponse; // update key property when checking license var concreteInstance = ret as LicenseResponse; concreteInstance.Raise(); return(concreteInstance as ILicenseResponse); } ; return(null); }
public Task <ILicenseResponse> PerformActionAsync(Consts.Action action, License License, RestSharp.Method httpMethod = RestSharp.Method.GET) { return(Task.Run(() => { return PerformAction(action, License); })); }
public async Task <May <T> > Execute <T>(Func <Task <T> > func, string resource = null, RestSharp.Method method = RestSharp.Method.GET) { var context = new RequestContext <T> { Resource = resource, Method = method, Execute = func }; var pipeline = _pipelineFactory.Build(); context = await pipeline.Handle(context); return(context.Data); }
string kokurl = "http://185.184.210.20:8080/api/";//main public string ServisIslem(string url, string istekler, bool isLogin = false, string Method = "POST", string ContentType = "application/json", bool UsePoll = false, bool localip = false, bool DontUseHostURL = false) { RestSharp.Method GelenMethod = RestSharp.Method.POST; if (UsePoll) { kokurl = "http://185.184.210.20:8080/services/pool/api/"; } if (localip) { kokurl = "http://192.168.1.38:8080/api/";//Lokal İP } switch (Method) { case "POST": GelenMethod = RestSharp.Method.POST; break; case "PUT": GelenMethod = RestSharp.Method.PUT; break; case "DELETE": GelenMethod = RestSharp.Method.DELETE; break; default: break; } RestSharp.RestClient client; client = new RestSharp.RestClient(kokurl + url); if (DontUseHostURL) { client = new RestSharp.RestClient(url); } client.Timeout = -1; var request = new RestSharp.RestRequest(GelenMethod); request.AddHeader("Content-Type", ContentType); if (!isLogin) { request.AddHeader("Authorization", "Bearer " + GetApiToken()); // request.AddParameter("Bearer", DataBase.MEMBER_DATA_GETIR()[0].API_TOKEN, RestSharp.ParameterType.Cookie); } request.AddParameter(ContentType, istekler, RestSharp.ParameterType.RequestBody); RestSharp.IRestResponse response = client.Execute(request); if (response.StatusCode != HttpStatusCode.Unauthorized && response.StatusCode != HttpStatusCode.InternalServerError && response.StatusCode != HttpStatusCode.BadRequest && response.StatusCode != HttpStatusCode.Forbidden && response.StatusCode != HttpStatusCode.MethodNotAllowed && response.StatusCode != HttpStatusCode.NotAcceptable && response.StatusCode != HttpStatusCode.RequestTimeout && response.StatusCode != HttpStatusCode.NotFound) { return(response.Content); } else { return("Hata"); } }