Last active
February 4, 2017 06:19
-
-
Save jonathanpeppers/c957f3f67d1a0f2994bd5501923c348d to your computer and use it in GitHub Desktop.
JsonContent for writing gzipped JSON in web requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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