private static Object CallTokenApi(ApiClient apiClient, String path, RestSharp.Method method, Dictionary <String, String> queryParams, Object postBody, Dictionary <String, String> headerParams, Dictionary <String, String> formParams, Dictionary <String, FileParameter> fileParams, Dictionary <String, String> pathParams, String contentType) { var regex = new Regex(@"://(api)\."); var authUrl = regex.Replace(apiClient.RestClient.BaseUrl.ToString(), "://login."); var restClient = new RestClient(authUrl); restClient.Proxy = apiClient.RestClient.Proxy; var request = PrepareTokenRequest( path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType); var response = restClient.Execute(request); int statusCode = (int)response.StatusCode; var fullUrl = restClient.BuildUri(request); string url = fullUrl == null ? path : fullUrl.ToString(); apiClient.Configuration.Logger.Trace(method.ToString(), url, postBody, statusCode, headerParams, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString())); apiClient.Configuration.Logger.Debug(method.ToString(), url, postBody, statusCode, headerParams); if (statusCode >= 400 || statusCode == 0) { apiClient.Configuration.Logger.Error(method.ToString(), url, postBody, response.Content, statusCode, headerParams, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString())); } return((Object)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="pathParams">Path parameters.</param> /// <param name="contentType">Content Type of the request</param> /// <returns>Object</returns> public Object CallApi( String path, RestSharp.Method method, List <Tuple <String, String> > queryParams, Object postBody, Dictionary <String, String> headerParams, Dictionary <String, String> formParams, Dictionary <String, FileParameter> fileParams, Dictionary <String, String> pathParams, String contentType) { var request = PrepareRequest( path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType); // set timeout RestClient.Timeout = Configuration.Timeout; // set user agent RestClient.UserAgent = Configuration.UserAgent; // Set SDK version request.AddHeader("purecloud-sdk", "151.0.0"); Retry retry = new Retry(this.RetryConfig); IRestResponse response; var fullUrl = RestClient.BuildUri(request); string url = fullUrl == null ? path : fullUrl.ToString(); do { response = RestClient.Execute(request); Configuration.Logger.Debug(method.ToString(), url, postBody, (int)response.StatusCode, headerParams); Configuration.Logger.Trace(method.ToString(), url, postBody, (int)response.StatusCode, headerParams, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString())); }while(retry.ShouldRetry(response)); if (UsingCodeAuth && Configuration.ShouldRefreshAccessToken) { int statusCode = (int)response.StatusCode; if (statusCode == 401) { HandleExpiredAccessToken(); headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; return(CallApi(path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType)); } } if ((int)response.StatusCode < 200 || (int)response.StatusCode >= 300) { Configuration.Logger.Error(method.ToString(), url, postBody, response.Content, (int)response.StatusCode, headerParams, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString())); } return((Object)response); }
public string Send(string url, object data, RestSharp.Method method) { var jsonData = JsonConvert.SerializeObject(data); Console.WriteLine($"Send: {method.ToString()} {url} | {jsonData}"); //ReconnectIfTimeouted(); var request = new RestRequest(url, method); request.AddCookie("sessionId", loginToken); request.AddJsonBody(jsonData); IRestResponse response = restClient.Execute(request); Console.WriteLine($"Respone: {response.Content}"); if (response.Content.StartsWith("<HTML>")) { return("{}"); } var returnValue = JsonConvert.DeserializeObject <Dictionary <string, string> >(response.Content); if (returnValue.ContainsKey("message")) { return("{}"); } else { return(response.Content); } }
public string invokeCommand(RestSharp.Method method, string resource, string parameters, object obj, RestSharp.Serializers.ISerializer serializer, out IList <Parameter> headers) { string full_resource = resource; if (parameters != null) { full_resource += "?" + parameters; } RestRequest request = new RestRequest(full_resource, method); request.RequestFormat = DataFormat.Xml; if (serializer != null) { request.XmlSerializer = serializer; } if ((method == Method.POST) || (method == Method.PUT)) { request.AddBody(obj); } long unixTimeStamp = GetCurrentUnixTimestampMillis(); string toSign = api_access_id + ":" + method.ToString() + ":" + resource + ":" + unixTimeStamp.ToString() + ":" + client.UserAgent; var signature = sign(secret_key, toSign); request.AddHeader("x-esauth-access", api_access_id); request.AddHeader("x-esauth-signature", signature); request.AddHeader("x-esauth-timestamp", unixTimeStamp.ToString()); if (additionalHeaders != null) { foreach (var di in additionalHeaders) { request.AddHeader(di.Key, di.Value); } } //request.AddHeader("x-es-with-perms", "false"); var response = client.Execute(request); headers = response.Headers; return(response.Content); // no need to aggregate the responses. simply return the non-paginated content. }
public void prepare_auth_header(string resource_path, RestSharp.Method method, Object body, Dictionary <String, String> query_params) { string _body; if (body == null) { _body = ""; } else { _body = body.ToString(); } Uri myUri = new Uri(host); string target_host = myUri.Host; string target_path = myUri.LocalPath; string request_target = method.ToString() + " " + target_path + resource_path; if (query_params != null && query_params.Count > 0) { string raw_query = ""; int count = 0; foreach (var item in query_params) { count++; if (count == 1) { raw_query = item.Key.ToString() + "=" + item.Value.ToString(); //break; } else { raw_query = raw_query + "&" + item.Key.ToString() + "=" + item.Value.ToString(); } } string str = ""; try { str = System.Web.HttpUtility.UrlEncode(raw_query); } catch (Exception ex) { Console.WriteLine("Exception : " + ex); } //Console.WriteLine("new URL " + request_target + "?" + str); //raw_query = raw_query.Replace(" ", "%20"); //raw_query = raw_query.Replace("$", "%24"); //raw_query = raw_query.Replace("'", "%27"); //request_target += "?" + raw_query; str = str.Replace("+", "%20"); str = str.Replace("%3d", "="); str = str.Replace("%26", "&"); request_target = request_target + "?" + str; } DateTime now = DateTime.Now; DateTime date1 = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second); string cdate = date1.ToUniversalTime().ToString("r"); byte[] body_digest = get_sha256_digest(_body); Dictionary <String, String> headers = new Dictionary <string, string>(); headers.Add("Date", cdate); headers.Add("Host", target_host); headers.Add("Content-Type", "application/json"); headers.Add("Digest", string.Format("SHA-256={0}", Convert.ToBase64String(body_digest))); string string_to_sign = prepare_str_to_sign(request_target, headers); byte[] digest = get_sha256_digest(string_to_sign); string b64_signed_msg = get_rsasig_b64encode(private_key_file, digest); string auth_header = get_auth_header(headers, b64_signed_msg); Configuration.AddDefaultHeader("Date", string.Format("{0}", (cdate))); Configuration.AddDefaultHeader("Host", string.Format("{0}", (target_host))); Configuration.AddDefaultHeader("Digest", string.Format("SHA-256={0}", Convert.ToBase64String(body_digest))); Configuration.AddDefaultHeader("Authorization", string.Format("{0}", (auth_header))); ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback( delegate { return(true); } ); }
// Creates and sets up a HttpWebRequest for calls which needs response in a file format. private HttpWebRequest PrepareHttpWebRequest( String path, RestSharp.Method method, Dictionary <String, String> queryParams, Object postBody, Dictionary <String, String> headerParams, Dictionary <String, String> formParams, Dictionary <String, FileParameter> fileParams, Dictionary <String, String> pathParams, String contentType) { // Change to path(Request Target) to be sent to Authentication SDK // Include Query Params in the Request target var firstQueryParam = true; foreach (var param in queryParams) { var key = param.Key; var val = param.Value; if (!firstQueryParam) { path = path + "&" + key + "=" + val; } else { path = path + "?" + key + "=" + val; firstQueryParam = false; } } //initiate a HttpWebRequest object HttpWebRequest requestT = (HttpWebRequest)WebRequest.Create(Uri.EscapeUriString("https://" + RestClient.BaseUrl.Host + path)); requestT.UserAgent = Configuration.UserAgent; if (Configuration.Proxy != null) { requestT.Proxy = Configuration.Proxy; } requestT.ContentType = contentType; // add header parameter, if any // passed to this function foreach (var param in headerParams) { if (param.Key == "Accept") { requestT.Accept = param.Value; } else { requestT.Headers.Add(param.Key, param.Value); } } //initiate the default authentication headers if (postBody == null) { CallAuthenticationHeaders(method.ToString(), path); } else { CallAuthenticationHeaders(method.ToString(), path, postBody.ToString()); } foreach (var param in Configuration.DefaultHeader) { if (param.Key == "Authorization") { requestT.Headers.Add("Authorization", string.Format("Bearer " + param.Value)); } else if (param.Key == "Date") { requestT.Date = DateTime.Parse(param.Value); } else if (param.Key == "Host") { } else { requestT.Headers.Add(param.Key, param.Value); } } return(requestT); }
// Creates and sets up a RestRequest prior to a call. private RestRequest PrepareRequest( String path, RestSharp.Method method, Dictionary <String, String> queryParams, Object postBody, Dictionary <String, String> headerParams, Dictionary <String, String> formParams, Dictionary <String, FileParameter> fileParams, Dictionary <String, String> pathParams, String contentType) { //1.set in the defaultHeaders of configuration // Change to path(Request Target) to be sent to Authentication SDK // Include Query Params in the Request target var firstQueryParam = true; foreach (var param in queryParams) { var key = param.Key; var val = param.Value; if (!firstQueryParam) { path = path + "&" + key + "=" + val; } else { path = path + "?" + key + "=" + val; firstQueryParam = false; } } var request = new RestRequest(path, method); // add path parameter, if any foreach (var param in pathParams) { request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment); } // add header parameter, if any // 2. passed to this function foreach (var param in headerParams) { if (param.Key == "Authorization") { request.AddParameter("Authorization", string.Format("Bearer " + param.Value), ParameterType.HttpHeader); } else { request.AddHeader(param.Key, param.Value); } } if (postBody == null) { CallAuthenticationHeaders(method.ToString(), path); } else { CallAuthenticationHeaders(method.ToString(), path, postBody.ToString()); } foreach (var param in Configuration.DefaultHeader) { if (param.Key == "Authorization") { request.AddParameter("Authorization", string.Format("Bearer " + param.Value), ParameterType.HttpHeader); } else { request.AddHeader(param.Key, param.Value); } } // add query parameter, if any // foreach(var param in queryParams) // request.AddQueryParameter(param.Key, param.Value); // add form parameter, if any foreach (var param in formParams) { request.AddParameter(param.Key, param.Value); } // add file parameter, if any foreach (var param in fileParams) { request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentLength, param.Value.ContentType); } if (postBody != null) // http body (model or byte[]) parameter { if (postBody.GetType() == typeof(String)) { request.AddParameter("application/json", postBody, ParameterType.RequestBody); } else if (postBody.GetType() == typeof(byte[])) { request.AddParameter(contentType, postBody, ParameterType.RequestBody); } } return(request); }