Beispiel #1
0
        public async Task <T> Invoke <T>(INetActionConfig action)
        {
            try
            {
                using (var requestBuilder = new Request.Builder())
                {
                    if (_netService.Config.HasCredentials)
                    {
                        requestBuilder.AddHeader("Authentication",
                                                 Credentials.Basic(_netService.Config.UserName, _netService.Config.Password ?? ""));
                    }

                    requestBuilder.Url(GetUri(action));

                    if (action.Payload != null)
                    {
                        requestBuilder.Post(
                            GetBody(action));
                    }

                    using (var request = requestBuilder.Build())
                    {
                        using (var clientBuilder = new OkHttpClient.Builder())
                        {
                            // Setup Client here
                            using (var client = clientBuilder.Build())
                            {
                                using (var response = await client.NewCall(request).ExecuteAsync().ConfigureAwait(false)
                                       )
                                {
                                    if (!response.IsSuccessful)
                                    {
                                        throw new Exception($"Error: code:{response.Code()}, msg:{response.Message()}");
                                    }

                                    using (var contentType = response.Body().ContentType())
                                    {
                                        _logger.Info(contentType);

                                        if (contentType.Type().EndsWith("xml"))
                                        {
                                            var body = await response.Body().StringAsync();

                                            return(Deserialize <T>(body));
                                        }

                                        if (contentType.Type().EndsWith("json"))
                                        {
                                            return(JsonConvert.DeserializeObject <T>(
                                                       await response.Body().StringAsync()));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _logger.Error(e);
            }

            return(default(T));
        }