Exemplo n.º 1
0
        public static async Task <object> RequestServiceStream <T>(BaseApiRequest request)
        {
            var url        = request.Endpoint;
            var httpClient = new HttpClient();

            Console.WriteLine($"Begin {request.RequestMethod}: {url}");

            HttpResponseMessage response = null;

            if (request.RequestMethod == HttpMethod.Get)
            {
                response = await httpClient.GetAsync(url);
            }
            else
            {
                response = await httpClient.PostAsync(url, request.RequestContent);
            }

            var bytes = await response.Content.ReadAsByteArrayAsync();

            if (bytes[0] == (byte)'{')
            {
                var szResponse = Encoding.UTF8.GetString(bytes);
                var result     = JsonConvert.DeserializeObject <T>(szResponse);
                return(result);
            }

            return(bytes);
        }
Exemplo n.º 2
0
        public static async Task <T> RequestService <T>(BaseApiRequest request, ResponseContentType contentType = ResponseContentType.Json) where T : BaseApiResponse
        {
            var url        = request.Endpoint;
            var httpClient = new HttpClient();

            Console.WriteLine($"Begin {request.RequestMethod}: {url}");

            HttpResponseMessage response = null;

            if (request.RequestMethod == HttpMethod.Get)
            {
                response = await httpClient.GetAsync(url);
            }
            else
            {
                response = await httpClient.PostAsync(url, request.RequestContent);
            }

            var apiResult = await response.Content.ReadAsStringAsync();

            Console.WriteLine("ApiResult:");
            Console.WriteLine(apiResult);

            var result = default(T);

            switch (contentType)
            {
            case ResponseContentType.Xml:
                using (StringReader reader = new StringReader(apiResult))
                {
                    var serializer = new XmlSerializer(typeof(T), new XmlRootAttribute("xml"));
                    result = (T)serializer.Deserialize(reader);
                }
                break;

            case ResponseContentType.Json:
                result = JsonConvert.DeserializeObject <T>(apiResult);
                break;

            default:
                break;
            }

            Console.WriteLine($"Finish {request.RequestMethod}: {url} response:[{result.ErrCode}] {result.ErrMsg}");
            return(result);
        }