/// <summary>
        /// Intializes this instance of WebClient with settings values
        /// </summary>
        /// <param name="settings"></param>
        public HttpUtilsWebClient(HttpRequestSettings settings = null)
        {
            Settings = settings;

            if (settings != null)
            {
                if (settings.Credentials != null)
                {
                    Credentials = settings.Credentials;
                }

                if (settings.Proxy != null)
                {
                    Proxy = settings.Proxy;
                }

                if (settings.Encoding != null)
                {
                    Encoding = settings.Encoding;
                }

                if (settings.Headers != null)
                {
                    foreach (var header in settings.Headers)
                    {
                        Headers[header.Key] = header.Value;
                    }
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Retrieves bytes from the server
        /// </summary>
        /// <param name="settings"></param>
        /// <returns></returns>
        public static byte[] HttpRequestBytes(HttpRequestSettings settings)
        {
            var client = new HttpUtilsWebClient(settings);

            if (settings.Content != null)
            {
                if (!string.IsNullOrEmpty(settings.ContentType))
                {
                    client.Headers["Content-type"] = settings.ContentType;
                }

                if (settings.Content is string)
                {
                    settings.CapturedRequestContent = settings.Content as string;
                    settings.ResponseByteData       = client.UploadData(settings.Url, settings.HttpVerb, settings.Encoding.GetBytes(settings.CapturedRequestContent));
                }
                else if (settings.Content is byte[])
                {
                    settings.ResponseByteData = client.UploadData(settings.Url, settings.Content as byte[]);
                }
                else
                {
                    throw new ArgumentException("Data must be either string or byte[].");
                }
            }
            else
            {
                settings.ResponseByteData = client.DownloadData(settings.Url);
            }

            settings.Response = client.Response;

            return(settings.ResponseByteData);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Retrieves and Http request and returns data as a string.
        /// </summary>
        /// <param name="settings">Pass HTTP request configuration parameters object to set the URL, Verb, Headers, content and more</param>
        /// <returns>string of HTTP response</returns>
        public static string HttpRequestString(HttpRequestSettings settings)
        {
            var client = new HttpUtilsWebClient(settings);

            if (settings.Credentials != null)
            {
                client.Credentials = settings.Credentials;
            }

            if (settings.Proxy != null)
            {
                client.Proxy = settings.Proxy;
            }

            if (settings.Headers != null)
            {
                foreach (var header in settings.Headers)
                {
                    client.Headers[header.Key] = header.Value;
                }
            }


            if (settings.HttpVerb == "GET")
            {
                settings.CapturedResponseContent = client.DownloadString(settings.Url);
            }
            else
            {
                if (!string.IsNullOrEmpty(settings.ContentType))
                {
                    client.Headers["Content-type"] = settings.ContentType;
                }

                if (settings.Content is string)
                {
                    settings.CapturedRequestContent  = settings.Content as string;
                    settings.CapturedResponseContent = client.UploadString(settings.Url, settings.HttpVerb, settings.CapturedRequestContent);
                }
                else if (settings.Content is byte[])
                {
                    settings.ResponseByteData        = client.UploadData(settings.Url, settings.Content as byte[]);
                    settings.CapturedResponseContent = Encoding.UTF8.GetString(settings.ResponseByteData);
                }
                else
                {
                    throw new ArgumentException("Data must be either string or byte[].");
                }
            }

            settings.Response = client.Response;


            return(settings.CapturedResponseContent);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Makes an HTTP with option JSON data serialized from an object
        /// and parses the result from JSON back into an object.
        /// Assumes that the service returns a JSON response
        /// </summary>
        /// <typeparam name="TResultType">The type of the object returned</typeparam>
        /// <param name="settings"><see cref="HttpRequestSettings"/>
        /// Configuration object for the HTTP request made to the server.
        /// </param>
        /// <returns>deserialized value/object from returned JSON data</returns>
        public static TResultType JsonRequest <TResultType>(HttpRequestSettings settings)
        {
            var client = new HttpUtilsWebClient(settings);

            client.Headers.Add("Accept", "application/json");

            string jsonResult;

            if (settings.Content != null)
            {
                if (!string.IsNullOrEmpty(settings.ContentType))
                {
                    client.Headers["Content-type"] = settings.ContentType;
                }
                else
                {
                    client.Headers["Content-type"] = "application/json;charset=utf-8;";
                }

                if (!settings.IsRawData)
                {
                    settings.CapturedRequestContent = JsonSerializationUtils.Serialize(settings.Content,
                                                                                       throwExceptions: true);
                }
                else
                {
                    settings.CapturedRequestContent = settings.Content as string;
                }

                jsonResult = client.UploadString(settings.Url, settings.HttpVerb, settings.CapturedRequestContent);

                if (jsonResult == null)
                {
                    return(default(TResultType));
                }
            }
            else
            {
                jsonResult = client.DownloadString(settings.Url);
            }

            settings.CapturedResponseContent = jsonResult;
            settings.Response = client.Response;

            return((TResultType)JsonSerializationUtils.Deserialize(jsonResult, typeof(TResultType), true));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Retrieves and Http request and returns data as a string.
        /// </summary>
        /// <param name="settings">Pass HTTP request configuration parameters object to set the URL, Verb, Headers, content and more</param>
        /// <returns>string of HTTP response</returns>
        public static async Task <string> HttpRequestStringAsync(HttpRequestSettings settings)
        {
            var client = new HttpUtilsWebClient(settings);


            if (settings.HttpVerb == "GET")
            {
                settings.CapturedResponseContent = await client.DownloadStringTaskAsync(new Uri(settings.Url));
            }
            else
            {
                if (!string.IsNullOrEmpty(settings.ContentType))
                {
                    client.Headers["Content-type"] = settings.ContentType;
                }

                if (settings.Content is string)
                {
                    settings.CapturedRequestContent  = settings.Content as string;
                    settings.CapturedResponseContent = await client.UploadStringTaskAsync(settings.Url, settings.HttpVerb, settings.CapturedRequestContent);
                }
                else if (settings.Content is byte[])
                {
                    settings.ResponseByteData = await client.UploadDataTaskAsync(settings.Url, settings.Content as byte[]);

                    settings.CapturedResponseContent = Encoding.UTF8.GetString(settings.ResponseByteData);
                }
                else
                {
                    throw new ArgumentException("Data must be either string or byte[].");
                }
            }

            settings.Response = client.Response;

            return(settings.CapturedResponseContent);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Makes an HTTP with option JSON data serialized from an object
        /// and parses the result from JSON back into an object.
        /// Assumes that the service returns a JSON response
        /// </summary>
        /// <typeparam name="TResultType">The type of the object returned</typeparam>
        /// <param name="settings"><see cref="HttpRequestSettings"/>
        /// Configuration object for the HTTP request made to the server.
        /// </param>
        /// <returns>deserialized value/object from returned JSON data</returns>
        public static TResultType JsonRequest <TResultType>(HttpRequestSettings settings)
        {
            var client = new HttpUtilsWebClient();

            if (settings.Credentials != null)
            {
                client.Credentials = settings.Credentials;
            }

            if (settings.Proxy != null)
            {
                client.Proxy = settings.Proxy;
            }

            client.Headers.Add("Accept", "application/json");

            if (settings.Headers != null)
            {
                foreach (var header in settings.Headers)
                {
                    client.Headers[header.Key] = header.Value;
                }
            }

            string jsonResult;

            if (settings.HttpVerb == "GET")
            {
                jsonResult = client.DownloadString(settings.Url);
            }
            else
            {
                if (!string.IsNullOrEmpty(settings.ContentType))
                {
                    client.Headers["Content-type"] = settings.ContentType;
                }
                else
                {
                    client.Headers["Content-type"] = "application/json";
                }

                if (!settings.IsRawData)
                {
                    settings.CapturedRequestContent = JsonSerializationUtils.Serialize(settings.Content, throwExceptions: true);
                }
                else
                {
                    settings.CapturedRequestContent = settings.Content as string;
                }

                jsonResult = client.UploadString(settings.Url, settings.HttpVerb, settings.CapturedRequestContent);

                if (jsonResult == null)
                {
                    return(default(TResultType));
                }
            }

            settings.CapturedResponseContent = jsonResult;
            settings.Response = client.Response;

            return((TResultType)JsonSerializationUtils.Deserialize(jsonResult, typeof(TResultType), true));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Creates a temporary image file from a download from a URL
        ///
        /// If you don't pass a file a temporary file is created in Temp Files folder.
        /// You're responsible for cleaning up the file after you are done with it.
        ///
        /// You should check the filename that is returned regardless of whether you
        /// passed in a filename - if the file is of a different image type the
        /// extension may be changed.
        /// </summary>
        /// <param name="filename">Url of image to download</param>
        /// <param name="imageUrl">Optional output image file. Filename may change extension if the image format doesn't match the filename.
        /// If not passed a temporary files file is created. Caller is responsible for cleaning up this file.
        /// </param>
        /// <param name="settings">Optional Http Settings for the request</param>
        public static async Task <string> DownloadImageToFileAsync(string imageUrl, string filename = null, HttpRequestSettings settings = null)
        {
            if (string.IsNullOrEmpty(imageUrl) ||
                !imageUrl.StartsWith("http://") && !imageUrl.StartsWith("https://"))
            {
                return(null);
            }

            string newFilename;

            if (string.IsNullOrEmpty(filename))
            {
                filename = Path.Combine(Path.GetTempPath(), "~img-" + DataUtils.GenerateUniqueId());
            }
            filename = Path.ChangeExtension(filename, "bin");

            var client = new HttpUtilsWebClient(settings);

            try
            {
                await client.DownloadFileTaskAsync(imageUrl, filename);

                var ct = client.ResponseHeaders[HttpRequestHeader.ContentType];

                var ext = ImageUtils.GetExtensionFromMediaType(ct);
                if (ext == null)
                {
                    return(null); // invalid image type
                }
                newFilename = Path.ChangeExtension(filename, ext);


                if (File.Exists(newFilename))
                {
                    File.Delete(newFilename);
                }

                // rename the file
                File.Move(filename, newFilename);
            }
            catch
            {
                if (File.Exists(filename))
                {
                    File.Delete(filename);
                }

                return(null);
            }

            return(newFilename);
        }
 public HttpUtilsWebClient(HttpRequestSettings settings = null)
 {
     Settings = settings;
 }