Skip to content

Instantly share code, notes, and snippets.

@jonathanpeppers
Last active February 4, 2017 06:19
Show Gist options
  • Select an option

  • Save jonathanpeppers/c957f3f67d1a0f2994bd5501923c348d to your computer and use it in GitHub Desktop.

Select an option

Save jonathanpeppers/c957f3f67d1a0f2994bd5501923c348d to your computer and use it in GitHub Desktop.
JsonContent for writing gzipped JSON in web requests
public class JsonContent : HttpContent
{
private readonly JsonSerializer _serializer = new JsonSerializer();
private readonly object _value;
public JsonContent(object value)
{
_value = value;
Headers.ContentType = new MediaTypeHeaderValue("application/gzip");
}
protected override bool TryComputeLength(out long length)
{
length = -1;
return false;
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
return Task.Factory.StartNew(() =>
{
using (var gzip = new GZipStream(stream, CompressionMode.Compress, true))
using (var writer = new StreamWriter(gzip))
{
_serializer.Serialize(writer, _value);
}
});
}
}
//To use it
var request = new HttpRequestMessage(HttpMethod.Post, "http://chucknorris.com/api/dropkick");
request.Content = new JsonContent(yourObjectToSerialize);
var response = await _httpClient.SendAsync(request);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment