예제 #1
0
        /// <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 <KeyValuePair <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;

            InterceptRequest(request);
            var response = RestClient.Execute(request);

            InterceptResponse(request, response);

            return((Object)response);
        }
예제 #2
0
        public static string GetRequestJson(RestSharp.Method method, string strrequest, object parameter = null)
        {
            CheckUxLauncher();
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            ServicePointManager.ServerCertificateValidationCallback = (RemoteCertificateValidationCallback)Delegate.Combine(ServicePointManager.ServerCertificateValidationCallback, new RemoteCertificateValidationCallback(NetClass.NewClass.Main));
            RestClient restClient = new RestClient("https://127.0.0.1:" + port)
            {
                Authenticator = new HttpBasicAuthenticator("riot", token)
            };
            RestRequest request = new RestRequest(strrequest, method, DataFormat.Json);

            if (method == Method.PUT && DataFormat.Json == DataFormat.Json)
            {
                request.AddJsonBody(parameter);
            }
            else if (method == Method.POST)
            {
                request.AddJsonBody(parameter);
            }
            var result = restClient.Execute(request);

            return(result.Content);
        }
예제 #3
0
        /// <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);

            // request.Credentials  = new NetworkCredential("Shakti", "P@ssw1234", "http://52.191.118.216:80/reports/");
            request.Credentials = new NetworkCredential("mai", "P@ssw509", "http://52.191.118.216:80/reports/");
            // request.Credentials = new NetworkCredential("Shakti", "P@ssw1234", "http://biolog-sqlvm:80/reports/");

            //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));
        }
예제 #4
0
        private void DoSend(RSharp.Method method, object body)
        {
            _request.AddParameter(
                "application/json",
                Newtonsoft.Json.JsonConvert.SerializeObject(body),
                ParameterType.RequestBody);

            _request.Timeout = 100000; // ms


            //Console.WriteLine("body: " + Newtonsoft.Json.JsonConvert.SerializeObject(body));

            var response = _restClient.Execute(_request, method);

            //Console.WriteLine("Error messag: e" + response.ErrorMessage);
            //Console.WriteLine("ResponseStatus: " + response.ResponseStatus.ToString());

            //Console.WriteLine("StatusDescription: " + response.StatusDescription);

            //Console.WriteLine("StatusCode: " + response.StatusCode);


            if (response.StatusCode == 0 && response.ErrorMessage.Contains("Section=ResponseStatusLine"))
            {
                return;
            }

            if (response.ErrorException != null)
            {
                throw RestClientFactory.CreateErrorException(_restClient, response);
            }

            if (!response.IsSuccessful)
            {
                throw RestClientFactory.CreateFailedException(_restClient, response);
            }
        }
예제 #5
0
        // Creates and sets up a RestRequest prior to a call.
        private RestRequest PrepareRequest(
            String path, RestSharp.Method method, List<KeyValuePair<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 = 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
            foreach(var param in headerParams)
                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.ContentType);
            }

            if (postBody != null) // http body (model or byte[]) parameter
            {
                request.AddParameter(contentType, postBody, ParameterType.RequestBody);
            }

            return request;
        }
        /// <summary>
        /// Adds the parameters that are required by the Last.Fm API to the <see cref="parameters"/> dictionary
        /// </summary>
        public static RestRequest AddRequiredParams(RestSharp.Method method, Dictionary <string, string> parameters, string methodName, Authentication authentication, bool addApiSignature = true)
        {
            var request = new RestRequest(method);



            // method
            parameters.Add(MethodParamName, methodName);

            // api key
            parameters.Add(ApiKeyParamName, authentication.ApiKey);

            // session key
            if (authentication.Session != null)
            {
                parameters.Add(SessionKeyParamName, authentication.Session.Key);
            }

            // api_sig
            if (addApiSignature)
            {
                parameters.Add(ApiSignatureParamName, GetApiSignature(parameters, authentication.ApiSecret));
            }

            // json
            parameters.Add("format", "json");

            foreach (var parameter in parameters)
            {
                request.AddParameter(parameter.Key, parameter.Value);
            }

            // JSonデコード
            request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };

            return(request);
        }
예제 #7
0
        /// <summary>
        /// Perform request to GatewayAPI
        /// </summary>
        private IRestResponse Request(RestSharp.Method method, string endPoint, string body = "")
        {
            var request = new RestSharp.RestRequest(endPoint, method);

            if (body != "")
            {
                request.AddJsonBody(body);
            }

            try
            {
                var response = client.Execute(request);

                if ((int)response.StatusCode != 200 && (int)response.StatusCode != 204)
                {
                    if ((int)response.StatusCode == 401)
                    {
                        throw new UnauthorizedException(response.Content);
                    }
                    else if ((int)response.StatusCode == 422)
                    {
                        throw new MessageException(response.Content);
                    }
                    else if ((int)response.StatusCode >= 500 || (int)response.StatusCode == 0)
                    {
                        throw new ServerException(response.Content);
                    }
                    throw new Exception(response.Content);
                }

                return(response);
            }
            catch (Exception e)
            {
                throw;
            }
        }
예제 #8
0
        public RestRequest CreateRequest(RestViewModal model)
        {
            RestSharp.Method method = Method.GET;
            switch (model.Method)
            {
            case Entity.Enum.Method.Post: { method = Method.POST; } break;

            case Entity.Enum.Method.Put: { method = Method.PUT; } break;

            case Entity.Enum.Method.Delete: { method = Method.DELETE; } break;
            }
            RestRequest request = new RestRequest(method);

            if (model.Data != null)
            {
                // request.AddJsonBody(model.Data);
                var    postData = JsonConvert.SerializeObject(model.Data);
                byte[] data     = Encoding.GetEncoding("UTF-8").GetBytes(postData);
                request.AddHeader("cache-control", "no-cache");
                request.AddParameter("application/json; charset=utf-8", data, ParameterType.RequestBody);
                request.AddJsonBody(data);
            }
            return(request);
        }
예제 #9
0
        public IRestRequest Build(string url, RestSharp.Method methodType, object urlSegment = null, object urlParameter = null)
        {
            var newRequest = new RestRequest(url, methodType);

            if (urlSegment != null)
            {
                PropertyInfo[] segments = urlSegment.GetType().GetProperties();
                foreach (var segment in segments)
                {
                    newRequest.AddUrlSegment(segment.Name, segment.GetValue(urlSegment));
                }
            }

            if (urlParameter != null)
            {
                PropertyInfo[] parameters = urlParameter.GetType().GetProperties();
                foreach (var parameter in parameters)
                {
                    newRequest.AddParameter(parameter.Name, parameter.GetValue(urlParameter));
                }
            }

            return(newRequest);
        }
예제 #10
0
        public string Request(RestSharp.Method method, string endPoint, Dictionary <string, object> headers, Dictionary <string, object> parameters, Dictionary <string, object> queryParameters, string body)
        {
            RestClient  client  = new RestClient(baseURL);
            RestRequest request = new RestRequest(endPoint, method);

            client.Authenticator = authenticator;
            foreach (var key in headers.Keys)
            {
                if (headers[key].GetType().ToString().StartsWith("System.Collections.Generics.List"))
                {
                    request.AddHeader(key, JsonConvert.SerializeObject(headers[key]));
                }
                else
                {
                    request.AddHeader(key, headers[key].ToString());
                }
            }
            foreach (var key in parameters.Keys)
            {
                request.AddParameter(key, parameters[key]);
            }
            foreach (var key in queryParameters.Keys)
            {
                if (headers[key].GetType().ToString().StartsWith("System.Collections.Generics.List"))
                {
                    request.AddQueryParameter(key, JsonConvert.SerializeObject(queryParameters[key]));
                }
                else
                {
                    request.AddQueryParameter(key, queryParameters[key].ToString());
                }
            }
            var response = client.Execute(request);

            return(response.Content);
        }
예제 #11
0
        /// <summary>
        /// Update parameters based on authentication.
        /// </summary>
        /// <param name="path">Request path.</param>
        /// <param name="method">Request method.</param>
        /// <param name="queryParams">Query parameters.</param>
        /// <param name="headerParams">Header parameters.</param>
        /// <param name="formParams">Form parameters.</param>
        /// <param name="authSettings">Authentication settings.</param>
        /// <param name="postBody">HTTP body (POST request).</param>
        public void UpdateParamsForAuth(String path, RestSharp.Method method, Dictionary <String, String> queryParams, Dictionary <String, String> headerParams, Dictionary <String, String> formParams, string[] authSettings, String postBody)
        {
            if (authSettings == null || authSettings.Length == 0)
            {
                return;
            }

            foreach (string auth in authSettings)
            {
                // determine which one to use
                switch (auth)
                {
                case "khipu":


                    headerParams["Authorization"] = AuthHeader(path, method, queryParams, formParams, postBody);
                    break;

                default:
                    //TODO show warning about security definition not found
                    break;
                }
            }
        }
예제 #12
0
        /// <summary>
        /// Makes the asynchronous HTTP request.
        /// </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.</param>
        /// <returns>The Task instance.</returns>
        public async System.Threading.Tasks.Task <Object> CallApiAsync(
            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 request = PrepareRequest(
                path, method, queryParams, postBody, headerParams, formParams, fileParams,
                pathParams, contentType);

            await InterceptRequestAsync(request);

            var response = await RestClient.ExecuteTaskAsync(request);

            if (!await InterceptResponseAsync(request, response) && authTriesCount < MAX_AUTH_TRIES_COUNT)
            {
                authTriesCount++;
                return(CallApiAsync(path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams,
                                    contentType));
            }

            authTriesCount = 0;
            return(response);
        }
        public RestSharp.Method DefinitionMethodRequest(string method)
        {
            RestSharp.Method methodReturn = RestSharp.Method.GET;
            switch (method)
            {
            case "POST":
                methodReturn = RestSharp.Method.POST;
                break;

            case "PUT":
                methodReturn = RestSharp.Method.PUT;
                break;

            case "DELETE":
                methodReturn = RestSharp.Method.DELETE;
                break;

            case "PATCH":
                methodReturn = RestSharp.Method.POST;
                break;
            }

            return(methodReturn);
        }
예제 #14
0
        // 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)
        {
            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
            foreach (var param in headerParams)
            {
                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)
            {
                FileParameter file = new FileParameter
                {
                    Name          = param.Value.Name,
                    Writer        = param.Value.Writer,
                    FileName      = param.Value.FileName,
                    ContentType   = param.Value.ContentType,
                    ContentLength = param.Value.ContentLength
                };
                //request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType);
                request.Files.Add(file);
            }

            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);
        }
예제 #15
0
        private void setupDefaultRequest <CanVerbAttribute, MandatoryVerbAttribute, MandatoryVerbMultipleAttribute>(RestSharp.Method method)       // FIXME - choose better name for this method
        {
            cleanRESTRequest();

            request.Method = method;

            // Get the type of the class and it's properties
            Type classType = this.GetType();

            PropertyInfo[] properties = classType.GetProperties();

            List <string> mandatoryMultiples = new List <string>();

            // Go through each property
            foreach (PropertyInfo property in properties)
            {
                string propertyName = property.Name;

                // If the property has the attribute 'MandatoryVerbMultipleAttribute' then it means that it must be set
                // unless another MandatoryVerbMultipleAttribute property is set already.
                if (Attribute.IsDefined(property, typeof(MandatoryVerbMultipleAttribute)))
                {
                    mandatoryMultiples.Add(propertyName);
                }

                if (Attribute.IsDefined(property, typeof(CanVerbAttribute)))
                {
                    // If it's set, then add it to the request
                    if (isPropertySet(propertyName))
                    {
                        request.AddParameter(propertyName, getPropertyAsString(propertyName));
                    }
                }

                if (Attribute.IsDefined(property, typeof(MandatoryVerbAttribute)) && !isPropertySet(propertyName))
                {
                    // A mandatory property is not set, throw an exception.
                    throw new PMAPIRequestMissingPropertyException(propertyName);
                }

                if (!Attribute.IsDefined(property, typeof(CanVerbAttribute)))
                {
                    // This property should not be set. To avoid confusion, we will make sure that
                    // the property is not set.
                    if (isPropertySet(propertyName))
                    {
                        throw new PMAPIRequestPropertyNotAllowedWithVerbException(propertyName);
                    }
                }
            }
            if (mandatoryMultiples.Count > 0)
            {
                Boolean mandatoryMultiplesCheckPassed = false;
                foreach (string checkPropertyName in mandatoryMultiples)
                {
                    if (isPropertySet(checkPropertyName))
                    {
                        mandatoryMultiplesCheckPassed = true;
                        break;
                    }
                }
                if (!mandatoryMultiplesCheckPassed)
                {
                    throw new PMAPIRequestMissingPropertyException(string.Join(", ", mandatoryMultiples.ToArray())); // FIXME - needs own exception
                }
            }
        }
예제 #16
0
        internal static RestRequest CreateRequest(string baseURL, RestSharp.Method method, RestSharp.Authenticators.IAuthenticator authenticator,
                                                  string bucketName = null, bool secure = false, string objectName = null,
                                                  Dictionary <string, string> headerMap = null,
                                                  string contentType = "application/octet-stream",
                                                  object body        = null, string resourcePath = null)
        {
            utils.ValidateBucketName(bucketName);
            if (objectName != null)
            {
                utils.ValidateObjectName(objectName);
            }

            // Start with user specified endpoint
            string host = baseURL;

            string resource     = string.Empty;
            bool   usePathStyle = false;

            if (bucketName != null)
            {
                if (s3utils.IsAmazonEndPoint(baseURL))
                {
                    if (method == RestSharp.Method.PUT && objectName == null && resourcePath == null)
                    {
                        // use path style for make bucket to workaround "AuthorizationHeaderMalformed" error from s3.amazonaws.com
                        usePathStyle = true;
                    }
                    else if (resourcePath != null && resourcePath.Contains("location"))
                    {
                        // use path style for location query
                        usePathStyle = true;
                    }
                    else if (bucketName != null && bucketName.Contains(".") && secure)
                    {
                        // use path style where '.' in bucketName causes SSL certificate validation error
                        usePathStyle = true;
                    }
                    else if (method == RestSharp.Method.HEAD && secure)
                    {
                        usePathStyle = true;
                    }

                    if (usePathStyle)
                    {
                        resource += utils.UrlEncode(bucketName) + "/";
                    }
                }
                else
                {
                    resource += utils.UrlEncode(bucketName) + "/";
                }
            }
            if (objectName != null)
            {
                resource += utils.EncodePath(objectName);
            }

            // Append query string passed in
            if (resourcePath != null)
            {
                resource += resourcePath;
            }

            RestRequest request = new RestRequest(resource, method);

            if (body != null)
            {
                request.AddParameter(contentType, body, RestSharp.ParameterType.RequestBody);
            }

            if (headerMap != null)
            {
                foreach (var entry in headerMap)
                {
                    request.AddHeader(entry.Key, entry.Value);
                }
            }
            return(request);
        }
예제 #17
0
        Tuple <RestClient, RestRequest> Call(string url, Dictionary <string, string> data, RestSharp.Method method,
                                             Dictionary <string, string> headers, string body)
        {
            var restClient =
                new RestClient(url)
            {
                UserAgent = "daredevils"
            };

            var request = new RestRequest(method);

            request.AddHeader("Accept", "application/json");
            request.AddHeader("User-Agent", "daredevils");
            if (data.IsNotNullOrEmpty())
            {
                foreach (var item in data)
                {
                    request.AddParameter(item.Key, item.Value);
                }
            }

            if (headers.IsNotNullOrEmpty())
            {
                foreach (var item in headers)
                {
                    request.AddHeader(item.Key, item.Value);
                }
            }

            if (body.IsNotNullOrEmptyOrWhiteSpace())
            {
                request.RequestFormat = DataFormat.Json;
                request.AddParameter("application/json; charset=utf-8", body, ParameterType.RequestBody);
            }
            return(new Tuple <RestClient, RestRequest>(restClient, request));
        }
예제 #18
0
        public static Boolean PeticionesPostJsonRestFulRespuetaBool <T>(string urlBaseServicio, string nombreCapacidad, RestSharp.Method tipoPeticion, T objeto)
        {
            Boolean respuesta;
            Uri     baseUrl = new Uri(urlBaseServicio);
            var     cliente = new RestClient
            {
                BaseUrl = baseUrl
            };
            var request = new RestRequest(nombreCapacidad, tipoPeticion);

            request.AddHeader("Accept", "application/json");
            request.RequestFormat = DataFormat.Json;
            request.Parameters.Clear();

            if (_parametros.Count > 0)
            {
                foreach (var parametro in _parametros)
                {
                    request.AddParameter(parametro.Key, parametro.Value);
                }
            }

            request.AddBody(objeto);


            IRestResponse response = cliente.Execute(request);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                //var result = response.Content;
                respuesta = true;;
            }
            else
            {
                respuesta = false;
            }
            return(respuesta);
        }
예제 #19
0
        public override Object CallApi(
            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)
        {
            foreach (var x in pathParams)
            {
                path = path.Replace("{" + string.Format("{0}", x.Key) + "}", x.Value);
            }

            headerParams.Clear();
            prepare_auth_header(path, method, postBody, queryParams);
            headerParams.Add("Content-Type", "application/json");
            headerParams.Add("Accept", "application/json");

            foreach (var field in Configuration.DefaultHeader)
            {
                if (!headerParams.ContainsKey(field.Key))
                {
                    headerParams.Add(field.Key, field.Value);
                }
            }

            foreach (var x in queryParams)
            {
                string key   = x.Key;
                string value = x.Value;
            }

            Object response = base.CallApi(path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType);

            try {
                IRestResponse localVarResponse   = (IRestResponse)response;
                int           localVarStatusCode = (int)localVarResponse.StatusCode;
                if (localVarStatusCode != 200)
                {
                    Console.WriteLine("Status : " + localVarResponse.StatusDescription);
                    Console.WriteLine("Status Code: " + localVarStatusCode);
                    foreach (var list in localVarResponse.Headers)
                    {
                        string property = list.ToString();
                        if (property.StartsWith("X-Starship-TraceId"))
                        {
                            Console.WriteLine("TraceId : " + property.Split('=')[1]);
                        }
                        else if (property.StartsWith("WWW-Authenticate"))
                        {
                            string[] fields = property.Split(new string[] { ", " }, StringSplitOptions.None);
                            foreach (var str in fields)
                            {
                                if (str.StartsWith("errorMessageId="))
                                {
                                    Console.WriteLine("Error Message ID : " + str.Split('=')[1]);
                                }
                                else if (str.StartsWith("errorMessage="))
                                {
                                    Console.WriteLine("Error Message : " + str.Split('=')[1]);
                                }
                            }
                        }
                    }
                }
            } catch (Exception ex)
            {
                Console.WriteLine("Internal error occured while parsing the response : " + ex.ToString());
            }
            return(response);
        }
        // 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);
        }
예제 #22
0
        /// <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>
        internal IRestResponse 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);


            if (headerParams == null)
            {
                headerParams = new Dictionary <string, string>();
            }
            if (!headerParams.ContainsKey("Authorization"))
            {
                if (this.AccessToken == null)
                {
                    throw new ApiException(400, "Missing required 'AccessToken' when calling the API");
                }
                if (this.TokenExpireDate.HasValue && this.TokenExpireDate < DateTime.UtcNow)
                {
                    if (this.RefreshToken == null)
                    {
                        throw new ApiException(400, "Expired 'AccessToken'");
                    }

                    RefreshAccessToken();
                }
                headerParams.Add("Authorization", this.ParameterToString("Bearer " + this.AccessToken));
            }

            // add header parameter, if any
            foreach (var param in headerParams)
            {
                request.AddHeader(param.Key, param.Value);
            }

            if (queryParams != null)
            {
                // add query parameter, if any
                foreach (var param in queryParams)
                {
                    request.AddParameter(param.Key, param.Value, ParameterType.GetOrPost);
                }
            }
            if (formParams != null)
            {
                // add form parameter, if any
                foreach (var param in formParams)
                {
                    request.AddParameter(param.Key, param.Value, ParameterType.GetOrPost);
                }
            }

            if (fileParams != null)
            {
                // 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) parameter
            {
                request.AddParameter("application/json", postBody, ParameterType.RequestBody);
            }

            var response = RestClient.Execute(request);

            if (((int)response.StatusCode) >= 400)
            {
                ApiError a = null;
                try
                {
                    if (response.Content != null && response.ContentType.StartsWith("application/json"))
                    {
                        a = JsonConvert.DeserializeObject <ApiError>(response.Content);
                    }
                }
                catch { }

                if (a != null)
                {
                    throw new ApiException((int)response.StatusCode, $"Error calling {method} {path}: {a.GetError()} {a.GetDescription()}",
                                           this.JsonPretty(request.Parameters.Where(p => p.Type == ParameterType.RequestBody).FirstOrDefault()?.Value) ?? string.Join("\r\n", request.Parameters.Where(x => x.Type != ParameterType.HttpHeader).Select(x => $"{x.Name}={x.Value}")));
                }
                else if (response.ContentType.StartsWith("text/html") || response.Content == null)
                {
                    throw new ApiException((int)response.StatusCode, $"Error calling {method} {path}: {(int)response.StatusCode} {response.StatusDescription}",
                                           this.JsonPretty(request.Parameters.Where(p => p.Type == ParameterType.RequestBody).FirstOrDefault()?.Value) ?? string.Join("\r\n", request.Parameters.Where(x => x.Type != ParameterType.HttpHeader).Select(x => $"{x.Name}={x.Value}")));
                }
                else
                {
                    throw new ApiException((int)response.StatusCode, $"Error calling {method} {path}: {(int)response.StatusCode} {response.Content}", response.Content);
                }
            }
            else if (((int)response.StatusCode) == 0)
            {
                throw new ApiException((int)response.StatusCode, $"Error calling {method} {path}: {response.ErrorMessage}", response.ErrorMessage);
            }

            var eTag = response.Headers.FirstOrDefault(x => x.Name == "ETag");

            if (eTag != null)
            {
                this.LastETag = eTag.Value.ToString();
            }


            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="pathParams">Path parameters.</param>
        /// <param name="contentType">Content Type of the request</param>
        /// <returns>Object</returns>
        public Object CallApi(
            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)
        {
            //declared separately to handle both regular call and download file calls
            int httpResponseStatusCode;
            IList <Parameter> httpResponseHeaders = null;
            string            httpResponseData    = string.Empty;

            var response = new RestResponse();

            if (!string.IsNullOrEmpty(AcceptHeader))
            {
                var defaultAcceptHeader = "," + headerParams["Accept"];
                defaultAcceptHeader = AcceptHeader + defaultAcceptHeader.Replace("," + AcceptHeader, "");
                headerParams.Remove("Accept");
                headerParams.Add("Accept", defaultAcceptHeader);
            }

            //check if the Response is to be downloaded as a file, this value to be set by the calling API class
            if (string.IsNullOrEmpty(DownloadReponseFileName))
            {
                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;

                RestClient.ClearHandlers();

                if (Configuration.Proxy != null)
                {
                    RestClient.Proxy = Configuration.Proxy;
                }

                InterceptRequest(request);
                response = (RestResponse)RestClient.Execute(request);
                InterceptResponse(request, response);
            }
            else
            {
                //prepare a HttpWebRequest request object
                var requestT = PrepareHttpWebRequest(path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType);

                //getting the response stream using httpwebrequest
                HttpWebResponse responseT = (HttpWebResponse)requestT.GetResponse();
                using (Stream responseStream = responseT.GetResponseStream())
                {
                    try
                    {
                        //setting high timeout to accomodate large files till 2GB, need to revisit for a dynamic approach
                        responseStream.ReadTimeout  = 8000000;
                        responseStream.WriteTimeout = 9000000;
                        using (Stream fileStream = File.OpenWrite(@DownloadReponseFileName))
                        {
                            byte[] buffer    = new byte[4096];
                            int    bytesRead = responseStream.Read(buffer, 0, 4096);
                            while (bytesRead > 0)
                            {
                                fileStream.Write(buffer, 0, bytesRead);
                                bytesRead = responseStream.Read(buffer, 0, 4096);
                            }
                        }
                    }
                    catch (Exception)
                    {
                        throw new ApiException(-1, $"Error writing to path : {DownloadReponseFileName}");
                    }
                }

                //setting the generic response with response headers
                foreach (var header in responseT.Headers)
                {
                    response.Headers.Add(new Parameter(header.ToString(), String.Join(",", responseT.Headers.GetValues(header.ToString()).ToArray()), ParameterType.HttpHeader));
                }

                //setting the generic RestResponse which is returned to the calling class
                response.StatusCode = responseT.StatusCode;
                if (responseT.StatusCode == HttpStatusCode.OK)
                {
                    response.Content = "Custom Message: Response downloaded to file " + DownloadReponseFileName;
                }
                else if (responseT.StatusCode == HttpStatusCode.NotFound)
                {
                    response.Content = "Custom Message: The requested resource is not found. Please try again later.";
                }
                else
                {
                    response.Content = responseT.StatusDescription;
                }
            }

            Configuration.DefaultHeader.Clear();

            httpResponseStatusCode = (int)response.StatusCode;
            httpResponseHeaders    = response.Headers;
            httpResponseData       = response.Content;

            Console.WriteLine($"\n");
            Console.WriteLine($"RESPONSE STATUS CODE: {httpResponseStatusCode}");

            Console.WriteLine($"\n");
            Console.WriteLine("RESPONSE HEADERS:-");

            foreach (var header in httpResponseHeaders)
            {
                Console.WriteLine(header);
            }
            Console.WriteLine($"\n");

            if (!string.IsNullOrEmpty(httpResponseData))
            {
                Console.WriteLine("RESPONSE BODY:-");
                Console.WriteLine(httpResponseData);
                Console.WriteLine($"\n");
            }

            return((Object)response);
        }
예제 #24
0
        private RestRequest CreateRequest <T>(ContractRequest <T> request, string url, RestSharp.Method method)
            where T : class
        {
            var json           = Newtonsoft.Json.JsonConvert.SerializeObject(request);
            var requestService = new RestRequest(url, method);

            requestService.AddHeader("Cache-Control", "no-cache");
            requestService.AddHeader("Content-Type", "application/json; charset-utf-8");
            requestService.AddParameter("application/json", json, ParameterType.RequestBody);

            return(requestService);
        }
예제 #25
0
        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); }
                );
        }
예제 #26
0
 private ChatterResponse MakeUserRestCall(string userId, string call, RestSharp.Method method, Dictionary <string, string> postParams)
 {
     return(MakeRestCall("users/" + userId + "/" + call, method, postParams));
 }
예제 #27
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="urlBaseServicio"></param>
        /// <param name="nombreCapacidad"></param>
        /// <param name="tipoPeticion"></param>
        /// <returns></returns>
        ///
        public static T ObtenerObjetoJsonRestFul <T>(string urlBaseServicio, string nombreCapacidad, RestSharp.Method tipoPeticion)
        {
            T   respuesta;
            Uri baseUrl = new Uri(urlBaseServicio);
            var cliente = new RestClient
            {
                BaseUrl = baseUrl
            };

            var request = new RestRequest(nombreCapacidad, tipoPeticion);

            request.Parameters.Clear();
            if (_parametros.Count > 0)
            {
                foreach (var parametro in _parametros)
                {
                    request.AddParameter(parametro.Key, parametro.Value);
                }
            }
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json");

            IRestResponse response = cliente.Execute(request);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var result = response.Content;
                respuesta = Newtonsoft.Json.JsonConvert.DeserializeObject <T>(result);
            }
            else
            {
                return(default(T));
            }
            return(respuesta);
        }
예제 #28
0
        private static IRestResponse <T> GetApiInfo(apiurl requesturl, string url, object pars, RestSharp.Method type, string Token = "", string ContentType = "")
        {
            var request = new RestRequest(type);

            if (pars != null)
            {
                request.AddObject(pars);
            }
            if (!ContentType.IsEmpty())
            {
                request.AddHeader("Content-Type", "application/json; charset=utf-8");
            }
            string baseutl = BaseConfigModel.Configuration[$"weburl:{requesturl.ToString()}"] + url;
            var    client  = new RestClient(baseutl);

            /*
             * 判断Token是否为,是否需要添加验证
             */
            if (!Token.IsEmpty())
            {
                request.AddHeader("Authorization", Token);
            }
            client.CookieContainer = new System.Net.CookieContainer();
            IRestResponse <T> reval = client.Execute <T>(request);

            if (reval.ErrorException != null)
            {
                // PubMethod.WirteExp(new Exception(reval.Content));
                throw new Exception("请求出错");
            }
            return(reval);
        }
예제 #29
0
        public static string PeticionesPostJsonRestFulRespuetastring(string urlBaseServicio, string nombreCapacidad, RestSharp.Method tipoPeticion)
        {
            string respuesta;
            Uri    baseUrl = new Uri(urlBaseServicio);
            var    cliente = new RestClient
            {
                BaseUrl = baseUrl
            };
            var request = new RestRequest(nombreCapacidad, tipoPeticion);

            // request.AddHeader("Accept", "application/json");
            //  request.RequestFormat = DataFormat.Json;
            request.Parameters.Clear();

            if (_parametros.Count > 0)
            {
                foreach (var parametro in _parametros)
                {
                    request.AddParameter(parametro.Key, parametro.Value);
                }
            }

            request.AddHeader("header", "value");
            IRestResponse response = cliente.Execute(request);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                respuesta = response.Content;
            }
            else
            {
                respuesta = "Sin respuesta";
            }
            return(respuesta);
        }
예제 #30
0
    public static T CallService <T>(RestFunctions objFunction, List <CParameter> lstParameters, RestSharp.Method Method) where T : new()
    {
        var         client  = new RestClient(BaseUrl);
        RestRequest request = new RestRequest(objFunction.ToString(), Method);

        foreach (CParameter objParameter in lstParameters)
        {
            request.AddParameter(objParameter.Key, objParameter.Value, objParameter.Type);
        }

        var response = client.Execute <T>(request);

        if (response.StatusDescription == "OK")
        {
            if (response.Data != null)
            {
                return(response.Data);
            }
            else
            {
                object[] temp = JsonConvert.DeserializeObject <object[]>(response.Content);
                var      arr  = (T)Convert.ChangeType(temp, typeof(T));

                string         EncondedText = HttpUtility.HtmlDecode(response.Content);
                JsonSerializer json         = new JsonSerializer();
                StringReader   sr           = new StringReader(EncondedText);
                JsonTextReader reader       = new JsonTextReader(sr);

                //T lst = JsonConvert.DeserializeObject<T>(response.Content);

                T data = (T)json.Deserialize(reader, typeof(T));
                //var data = JsonConvert.DeserializeObject<T>(response.Content);
                return(data);
            }
        }
        else
        {
            return(response.Data);
        }
    }