Ejemplo n.º 1
0
        private async Task <T> SendAsync <T>(HttpMethod method, IBitcoinSerializable body, string relativePath, params object[] parameters) where T : IBitcoinSerializable, new()
        {
            var uri     = GetFullUri(relativePath, parameters);
            var message = new HttpRequestMessage(method, uri);

            if (body != null)
            {
                message.Content = new ByteArrayContent(body.ToBytes());
            }

            var result = await Client.SendAsync(message).ConfigureAwait(false);

            if (!result.IsSuccessStatusCode)
            {
                string error = await result.Content.ReadAsStringAsync().ConfigureAwait(false);

                if (!string.IsNullOrEmpty(error))
                {
                    throw new HttpRequestException(result.StatusCode + ": " + error);
                }
            }
            if (result.StatusCode == HttpStatusCode.NotFound)
            {
                return(default(T));
            }
            if (result.Content?.Headers?.ContentLength > MaxContentLength)
            {
                Logs.Client.LogError($"Content is larger than max content length of {MaxContentLength}bytes for request to: {uri}\nRequest Body: \"{body.ToString()}\"");
                throw new IOException("Content is too big");
            }

            try
            {
                result.EnsureSuccessStatusCode();
            }
            catch (Exception ex)
            {
                Logs.Client.LogError(ex, $"Received HTTP {result.StatusCode} response from: {uri}\nRequest Body: \"{body.ToString()}\"");
                throw ex;
            }

            if (typeof(T) == typeof(byte[]))
            {
                return((T)(object)await result.Content.ReadAsByteArrayAsync().ConfigureAwait(false));
            }
            var str = await result.Content.ReadAsStringAsync().ConfigureAwait(false);

            if (typeof(T) == typeof(string))
            {
                return((T)(object)str);
            }

            var bytes = await result.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

            if (bytes.Length == 0)
            {
                return(default(T));
            }
            var stream = new BitcoinStream(new MemoryStream(bytes), false);

            var data = new T();

            stream.ReadWrite <T>(ref data);
            return(data);
        }