Customized version of WebClient that provides access to the Response object so we can read result data from the Response.
Наследование: System.Net.WebClient
Пример #1
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.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;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);
            }

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

            return (TResultType)JsonSerializationUtils.Deserialize(jsonResult, typeof(TResultType), true);
        }
Пример #2
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.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;
        }
Пример #3
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);
        }
Пример #4
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>
        /// <returns>image filename or null on failure. Note that the filename may have a different extension than the request filename parameter.</returns>
        public static string DownloadImageToFile(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
            {
                client.DownloadFile(imageUrl, filename);

                var ct = client.Response.ContentType;   // works

                if (string.IsNullOrEmpty(ct) || !ct.StartsWith("image/"))
                {
                    return(null);
                }

                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);
        }
Пример #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 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);
        }
Пример #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 and that
        /// any data sent is json.
        /// </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 async Task <TResultType> JsonRequestAsync <TResultType>(HttpRequestSettings settings)
        {
            var client = new HttpUtilsWebClient(settings);

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

            string jsonResult;

            if (settings.HttpVerb == "POST" || settings.HttpVerb == "PUT" || settings.HttpVerb == "PATCH")
            {
                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 = await client.UploadStringTaskAsync(settings.Url, settings.HttpVerb, settings.CapturedRequestContent);

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

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

            return((TResultType)JsonSerializationUtils.Deserialize(jsonResult, typeof(TResultType), true));
        }
Пример #7
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.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.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[].");
                }
            }
            else
            {
                settings.CapturedResponseContent = await client.DownloadStringTaskAsync(new Uri(settings.Url));
            }

            settings.Response = client.Response;

            return(settings.CapturedResponseContent);
        }
Пример #8
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));
        }