Getting the Content-Encoding header in C#

Jun 09, 10 Getting the Content-Encoding header in C#

Recently I needed to get the Content-Encoding header within a C# application.After trying to figure out why the response was empty, and after reading different community posts where other users had the same problem and none of the suggestions seem to solve it, I’ve decided to post my solution for further use.
Let’s take a look at how things stand.

The Problem

public static string GetEncoding(string url)
        {
            HttpWebRequest request;
            HttpWebResponse response;
            string result = null;

            try
            {
                request = (HttpWebRequest)WebRequest.Create(url);
                response = (HttpWebResponse)request.GetResponse();

                result = response.ContentEncoding;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            return result;
        }

        static void Main(string[] args)
        {
            Console.WriteLine(GetEncoding("http://microsoft.com"));
        }

We declare a HttpWebRequest and HttpWebResponse object, we create the request, get the response but when we try to see the ContentEncoding return message, it’s always empty, null.

The solution

public static string GetEncoding(string url)
        {
            HttpWebRequest request;
            HttpWebResponse response;
            string result = null;

            try
            {
                request = (HttpWebRequest)WebRequest.Create(url);
                request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");

                response = (HttpWebResponse)request.GetResponse();
                result = response.ContentEncoding;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            return result;
        }

        static void Main(string[] args)
        {
            Console.WriteLine(GetEncoding("http://microsoft.com"));
        }

The solution is to implicitly set the Accept-Encoding header to be sent with the request.We can do this either by using HttpRequestHeader.AcceptEncoding or by declaring as such:

request.Headers.Add("Accept-Encoding", "gzip,deflate");

Either way, it does the same thing.Now, after sending the Accept-Encoding header, we get the right response in the response.ContentEncoding.

I hope this article solved your issue.Stay tuned for more C# helpful articles.

Related posts:

  1. Using the params modifier in C#
  2. Singleton Design Pattern
  3. Introduction into Cryptography
  4. Extracting RSS Data with C# and XPath
  5. How to Login via Facebook in ASP.NET

3 Comments

  1. Langendorf /

    Thank you for sharing!

  2. ksj88ds /

    Good information, keep working man. I like your website. Cheers~~~~

  3. You’re more than welcome. Thanks for visiting!

Leave a Reply