コード例 #1
0
        public void Execute <T>(ServiceRequest serviceRequest, Action <ServiceRequest.Response <T> > completedhandler) where T : new()
        {
            if (serviceRequest == null)
            {
                SDKLogger.Instance.Error("serviceRequest is null.");
                completedhandler?.Invoke(new ServiceRequest.Response <T>()
                {
                    StatusCode = 0
                });
                return;
            }

            RestRequest request = new RestRequest(serviceRequest.Resource, (Method)serviceRequest.Method);

            if (serviceRequest.AccessToken != null)
            {
                request.AddHeader("Authorization", "Bearer " + serviceRequest.AccessToken);
            }

            foreach (var pair in serviceRequest.Headers)
            {
                request.AddHeader(pair.Key, pair.Value);
            }

            foreach (var pair in serviceRequest.QueryParameters)
            {
                request.AddParameter(pair.Key, pair.Value, ParameterType.GetOrPost);
            }

            foreach (var pair in serviceRequest.BodyParameters)
            {
                request.AddParameter(pair.Key, pair.Value, ParameterType.GetOrPost);
            }

            if (serviceRequest.RootElement.Length != 0)
            {
                request.RootElement = serviceRequest.RootElement;
            }
            //Cisco Spark platform is dropping support for TLS 1.0 as of March 16, 2018
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;

            var client = new RestClient()
            {
                BaseUrl = new System.Uri(serviceRequest.BaseUri)
            };


            SDKLogger.Instance.Info($"http request[{serviceRequest.Method.ToString()}]: {serviceRequest.BaseUri + request.Resource}");
            client.ExecuteAsync <T>(request, response =>
            {
                var r               = new ServiceRequest.Response <T>();
                r.StatusCode        = (int)response.StatusCode;
                r.StatusDescription = response.StatusDescription;
                r.Headers           = new List <KeyValuePair <string, object> >();
                foreach (var i in response.Headers)
                {
                    r.Headers.Add(new KeyValuePair <string, object>(i.Name, i.Value));
                }

                r.Data = response.Data;

                completedhandler?.Invoke(r);
            });
        }