/// <summary>
        /// Helper method to return an Xml document from the completed request.
        /// </summary>
        /// <param name="requestBaseUrl">The request base URL.</param>
        /// <param name="stream">The stream.</param>
        /// <param name="response">The response from the server.</param>
        private static DownloadResult <IXPathNavigable> GetXmlDocument(Uri requestBaseUrl, Stream stream,
                                                                       HttpResponseMessage response)
        {
            XmlDocument xmlDoc = new XmlDocument();
            HttpWebClientServiceException error = null;
            int      responseCode = (int)response.StatusCode;
            DateTime serverTime   = response.Headers.ServerTimeUTC();

            if (stream == null)
            {
                error = HttpWebClientServiceException.Exception(requestBaseUrl, new ArgumentNullException(nameof(stream)));
                return(new DownloadResult <IXPathNavigable>(xmlDoc, error, responseCode, serverTime));
            }

            try
            {
                xmlDoc.Load(Util.ZlibUncompress(stream));
            }
            catch (XmlException ex)
            {
                error = HttpWebClientServiceException.XmlException(requestBaseUrl, ex);
            }

            return(new DownloadResult <IXPathNavigable>(xmlDoc, error, responseCode, serverTime));
        }
示例#2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DownloadResult{T}"/> class.
 /// </summary>
 /// <param name="result">The result.</param>
 /// <param name="error">The error.</param>
 /// <param name="responseCode">The server response code.</param>
 public DownloadResult(T result, HttpWebClientServiceException error, int responseCode = 0)
 {
     Error        = error;
     Result       = result;
     ResponseCode = responseCode;
     ServerTime   = DateTime.UtcNow;
 }
示例#3
0
        /// <summary>
        /// Helper method to return a string from the completed request.
        /// </summary>
        /// <param name="requestBaseUrl">The request base URL.</param>
        /// <param name="stream">The stream.</param>
        /// <param name="response">The response from the server.</param>
        private static DownloadResult <string> GetString(Uri requestBaseUrl, Stream stream,
                                                         HttpResponseMessage response)
        {
            string text = string.Empty;
            HttpWebClientServiceException error = null;
            int      responseCode = (int)response.StatusCode;
            DateTime serverTime   = response.Headers.ServerTimeUTC();

            if (stream == null)
            {
                error = HttpWebClientServiceException.Exception(requestBaseUrl, new ArgumentNullException(nameof(stream)));
                return(new DownloadResult <string>(text, error, responseCode, serverTime));
            }

            try
            {
                using (StreamReader reader = new StreamReader(Util.ZlibUncompress(stream)))
                    text = reader.ReadToEnd();
            }
            catch (ArgumentException ex)
            {
                error = HttpWebClientServiceException.Exception(requestBaseUrl, ex);
            }

            return(new DownloadResult <string>(text, error, responseCode, serverTime));
        }
示例#4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DownloadResult{T}"/> class.
 /// </summary>
 /// <param name="result">The result.</param>
 /// <param name="error">The error.</param>
 /// <param name="response">The server response data.</param>
 public DownloadResult(T result, HttpWebClientServiceException error,
                       ResponseParams response = null)
 {
     Error    = error;
     Result   = result;
     Response = response ?? new ResponseParams(0);
 }
示例#5
0
        /// <summary>
        /// Gets the result.
        /// </summary>
        /// <param name="requestBaseUrl">The request base URL.</param>
        /// <param name="stream">The stream.</param>
        /// <param name="response">The response from the server.</param>
        /// <returns></returns>
        private static DownloadResult <Image> GetImage(Uri requestBaseUrl, Stream stream,
                                                       HttpResponseMessage response)
        {
            Image image = null;
            HttpWebClientServiceException error = null;
            int      responseCode = (int)response.StatusCode;
            DateTime serverTime   = response.Headers.ServerTimeUTC();

            if (stream == null)
            {
                error = HttpWebClientServiceException.Exception(requestBaseUrl, new ArgumentNullException(nameof(stream)));
                return(new DownloadResult <Image>(null, error, responseCode, serverTime));
            }

            try
            {
                image = Image.FromStream(Util.ZlibUncompress(stream), true);
            }
            catch (ArgumentException ex)
            {
                error = HttpWebClientServiceException.ImageException(requestBaseUrl, ex);
            }

            return(new DownloadResult <Image>(image, error, responseCode, serverTime));
        }
示例#6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DownloadResult{T}"/> class.
 /// </summary>
 /// <param name="result">The result.</param>
 /// <param name="error">The error.</param>
 /// <param name="responseCode">The server response code.</param>
 /// <param name="serverTime">The time on the server.</param>
 public DownloadResult(T result, HttpWebClientServiceException error, int responseCode,
                       DateTime serverTime)
 {
     Error        = error;
     Result       = result;
     ResponseCode = responseCode;
     ServerTime   = serverTime;
 }
        /// <summary>
        /// Helper method to return an object from the completed request stream.
        /// </summary>
        /// <param name="requestBaseUrl">The request base URL.</param>
        /// <param name="stream">The stream.</param>
        /// <param name="parser">The function which will parse the stream.</param>
        /// <param name="response">The response from the server.</param>
        /// <returns>The parsed object.</returns>
        private static DownloadResult <T> GetResult <T>(Uri requestBaseUrl, Stream stream,
                                                        ParseDataDelegate <T> parser, HttpResponseMessage response)
        {
            T result = default(T);
            HttpWebClientServiceException error = null;
            int      responseCode = (int)response.StatusCode;
            DateTime serverTime   = response.Headers.ServerTimeUTC();

            if (stream == null)
            {
                error = HttpWebClientServiceException.Exception(requestBaseUrl,
                                                                new ArgumentNullException(nameof(stream)));
                return(new DownloadResult <T>(result, error, responseCode, serverTime));
            }

            result = parser.Invoke(Util.ZlibUncompress(stream), responseCode);

            return(new DownloadResult <T>(result, error, responseCode, serverTime));
        }
        /// <summary>
        /// Helper method to return an object from the completed request stream.
        /// </summary>
        /// <param name="requestBaseUrl">The request base URL.</param>
        /// <param name="stream">The stream.</param>
        /// <param name="parser">The function which will parse the stream.</param>
        /// <param name="response">The response from the server.</param>
        /// <returns>The parsed object.</returns>
        private static DownloadResult <T> GetResult <T>(Uri requestBaseUrl, Stream stream,
                                                        ParseDataDelegate <T> parser, HttpResponseMessage response)
        {
            T result = default(T);
            HttpWebClientServiceException error = null;
            var param = new ResponseParams(response);

            if (stream == null)
            {
                // No stream (can this happen)?
                error = HttpWebClientServiceException.Exception(requestBaseUrl,
                                                                new ArgumentNullException(nameof(stream)));
            }
            else
            {
                // Attempt to invoke parser
                result = parser.Invoke(Util.ZlibUncompress(stream), param);
            }
            return(new DownloadResult <T>(result, error, param));
        }
        /// <summary>
        /// Gets the result.
        /// </summary>
        /// <param name="requestBaseUrl">The request base URL.</param>
        /// <param name="stream">The stream.</param>
        /// <returns></returns>
        private static DownloadResult <Image> GetImage(Uri requestBaseUrl, Stream stream)
        {
            Image image = null;
            HttpWebClientServiceException error = null;

            if (stream == null)
            {
                error = HttpWebClientServiceException.Exception(requestBaseUrl, new ArgumentNullException(nameof(stream)));
                return(new DownloadResult <Image>(null, error));
            }

            try
            {
                image = Image.FromStream(Util.ZlibUncompress(stream), true);
            }
            catch (ArgumentException ex)
            {
                error = HttpWebClientServiceException.ImageException(requestBaseUrl, ex);
            }

            return(new DownloadResult <Image>(image, error));
        }
示例#10
0
        /// <summary>
        /// Helper method to return an Xml document from the completed request.
        /// </summary>
        /// <param name="requestBaseUrl">The request base URL.</param>
        /// <param name="stream">The stream.</param>
        /// <returns></returns>
        private static DownloadResult <IXPathNavigable> GetXmlDocument(Uri requestBaseUrl, Stream stream)
        {
            XmlDocument xmlDoc = new XmlDocument();
            HttpWebClientServiceException error = null;

            if (stream == null)
            {
                error = HttpWebClientServiceException.Exception(requestBaseUrl, new ArgumentNullException(nameof(stream)));
                return(new DownloadResult <IXPathNavigable>(xmlDoc, error));
            }

            try
            {
                xmlDoc.Load(Util.ZlibUncompress(stream));
            }
            catch (XmlException ex)
            {
                error = HttpWebClientServiceException.XmlException(requestBaseUrl, ex);
            }

            return(new DownloadResult <IXPathNavigable>(xmlDoc, error));
        }
示例#11
0
        /// <summary>
        /// Helper method to return a string from the completed request.
        /// </summary>
        /// <param name="requestBaseUrl">The request base URL.</param>
        /// <param name="stream">The stream.</param>
        /// <returns></returns>
        private static DownloadResult <String> GetString(Uri requestBaseUrl, Stream stream)
        {
            String text = String.Empty;
            HttpWebClientServiceException error = null;

            if (stream == null)
            {
                error = HttpWebClientServiceException.Exception(requestBaseUrl, new ArgumentNullException(nameof(stream)));
                return(new DownloadResult <String>(text, error));
            }

            try
            {
                using (StreamReader reader = new StreamReader(Util.ZlibUncompress(stream)))
                    text = reader.ReadToEnd();
            }
            catch (ArgumentException ex)
            {
                error = HttpWebClientServiceException.Exception(requestBaseUrl, ex);
            }

            return(new DownloadResult <String>(text, error));
        }
        /// <summary>
        /// Asynchronously sends a request to the specified url.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="param">The request parameters.</param>
        /// <param name="accept">The content types to accept.</param>
        /// <returns></returns>
        public async Task <HttpResponseMessage> SendAsync(Uri url, RequestParams param,
                                                          string accept)
        {
            var newParams = param ?? new RequestParams();

            while (true)
            {
                // Store params
                m_url    = url;
                m_accept = accept;
                HttpResponseMessage response = null;
                try
                {
                    var request = GetHttpRequest(newParams);
                    response = await GetHttpResponseAsync(GetHttpClientHandler(), request).
                               ConfigureAwait(false);

                    EnsureSuccessStatusCode(response);
                }
                catch (HttpWebClientServiceException)
                {
                    // Seems pointless but prevents the exception from getting wrapped again
                    throw;
                }
                catch (HttpRequestException ex)
                {
                    // Strip a layer of exceptions if a web exception occurred
                    if (ex.InnerException is WebException)
                    {
                        throw HttpWebClientServiceException.HttpWebClientException(url,
                                                                                   ex.InnerException);
                    }
                    // Throw default exception if no response
                    if (response == null)
                    {
                        throw HttpWebClientServiceException.Exception(url, ex);
                    }
                    // Throw for 404, 500, etc.
                    if (response.StatusCode != HttpStatusCode.Redirect && response.
                        StatusCode != HttpStatusCode.MovedPermanently)
                    {
                        throw HttpWebClientServiceException.HttpWebClientException(url, ex,
                                                                                   response.StatusCode);
                    }
                }
                catch (TaskCanceledException ex)
                {
                    // We throw a request timeout if the task gets cancelled due to the
                    // timeout setting
                    throw HttpWebClientServiceException.HttpWebClientException(url,
                                                                               new HttpRequestException(ex.Message), HttpStatusCode.RequestTimeout);
                }
                catch (Exception ex)
                {
                    throw HttpWebClientServiceException.Exception(url, ex);
                }
                if (response.StatusCode != HttpStatusCode.Redirect && response.StatusCode !=
                    HttpStatusCode.MovedPermanently)
                {
                    return(response);
                }

                // When the address has been redirected, connects to the redirection
                Uri target = response.Headers.Location;
                response.Dispose();
                if (m_redirectsRemaining-- <= 0)
                {
                    throw HttpWebClientServiceException.RedirectsExceededException(m_url);
                }
                m_referrer = m_url;
                m_url      = new Uri(m_url, target);
                url        = m_url;
            }
        }
示例#13
0
        /// <summary>
        /// Asynchronously sends a request to the specified url.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="method">The method.</param>
        /// <param name="postData">The post data.</param>
        /// <param name="dataCompression">The data compression.</param>
        /// <param name="acceptEncoded">if set to <c>true</c> accept encoded response.</param>
        /// <param name="accept">The accept.</param>
        /// <returns></returns>
        public async Task <HttpResponseMessage> SendAsync(Uri url, HttpMethod method, HttpPostData postData,
                                                          DataCompression dataCompression,
                                                          bool acceptEncoded, string accept)
        {
            while (true)
            {
                // Store params
                m_url             = url;
                m_accept          = accept;
                m_postData        = postData;
                m_method          = postData == null || method == null ? HttpMethod.Get : method;
                m_dataCompression = postData == null ? DataCompression.None : dataCompression;
                m_acceptEncoded   = acceptEncoded;

                HttpResponseMessage response = null;
                try
                {
                    HttpClientHandler  httpClientHandler = GetHttpClientHandler();
                    HttpRequestMessage request           = GetHttpRequest();
                    response = await GetHttpResponseAsync(httpClientHandler, request).ConfigureAwait(false);

                    EnsureSuccessStatusCode(response);
                }
                catch (HttpWebClientServiceException)
                {
                    throw;
                }
                catch (HttpRequestException ex)
                {
                    if (ex.InnerException is WebException)
                    {
                        throw HttpWebClientServiceException.HttpWebClientException(url, ex.InnerException);
                    }

                    if (response == null)
                    {
                        throw HttpWebClientServiceException.Exception(url, ex);
                    }

                    if (response.StatusCode != HttpStatusCode.Redirect && response.StatusCode != HttpStatusCode.MovedPermanently)
                    {
                        throw HttpWebClientServiceException.HttpWebClientException(url, ex, response.StatusCode);
                    }
                }
                catch (WebException ex)
                {
                    // We should not get a WebException here but keep this as extra precaution
                    throw HttpWebClientServiceException.HttpWebClientException(url, ex);
                }
                catch (TaskCanceledException ex)
                {
                    // We throw a request timeout if the task gets cancelled due to the timeout setting
                    throw HttpWebClientServiceException.HttpWebClientException(url, new HttpRequestException(ex.Message),
                                                                               HttpStatusCode.RequestTimeout);
                }
                catch (Exception ex)
                {
                    throw HttpWebClientServiceException.Exception(url, ex);
                }

                if (response.StatusCode != HttpStatusCode.Redirect && response.StatusCode != HttpStatusCode.MovedPermanently)
                {
                    return(response);
                }

                // When the address has been redirected, connects to the redirection
                Uri target = response.Headers.Location;
                response.Dispose();

                if (m_redirectsRemaining-- <= 0)
                {
                    throw HttpWebClientServiceException.RedirectsExceededException(m_url);
                }

                m_referrer = m_url;
                m_url      = new Uri(m_url, target);
                url        = m_url;
            }
        }