Configuring your HttpClient to automagically decompress the response


Recently I was writing a simple HttpClient to interface with a REST API.  Typically I just pass the response string to a JSON converter and get my object out the other end.  However, in my case I was getting the following error from my converter:

Newtonsoft.Json.JsonReaderException was caught
_message=Unexpected character encountered while parsing value: . Path '', line 0, position 0.
Message=Unexpected character encountered while parsing value: . Path '', line 0, position 0.
at Newtonsoft.Json.JsonTextReader.ParseValue()
at Newtonsoft.Json.JsonTextReader.ReadInternal()
at Newtonsoft.Json.JsonTextReader.Read()
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)
at WSDSForumAPI.StackOverflow.<GetPostsForTag>d__0.MoveNext()

When I looked into the issue the string being passed to the converter looked like this:


I attached fiddler, and then realized that my response content was compressed, as the response had the following header:

Content-Encoding: gzip

So I set out to figure out how to decompress the content.   It turns out this is fairly simple.   Just create a HttpClientHandler and set its AutomaticDecompression to the type of compression used in the response.  The following code snippet is what I ended up with for my scenario:

Copy Code:

 HttpClientHandler handler = new HttpClientHandler(); handler.AutomaticDecompression = System.Net.DecompressionMethods.GZip; _client = new HttpClient(handler);

That is it for this blog post.  Simple and to the point.  Until next time have fun coding!

Don’t forget to follow the Windows Store Developer Solutions team on Twitter @wsdevsol. Comments are welcome, both below and on twitter.

- Bret Bentzinger(Microsoft) @awehellyeah