.NET 11 Preview - Using Zstandard Compression With A HttpClient
[C#, .NET, .NET 11 Preview]
Yesterday’s post, “NET 11 Preview - Zstandard Compression”, looked at the introduction of the Zstandard algorithm into the compression libraries in System.IO.Compression namespace.
In today’s post, we will look at how to use Zstandard compression with a HttpClient.
For this, we first write a HttpClientHandler like so:
var handler = new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.Zstandard
};
Here, we are setting the AutomaticDecompression property.
It is generally a good idea to specify an alternate compression if the web server does not support Zstandard, like so:
var handler = new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Zstandard
};
Here, we are specifying GZip or Zstandard.
Finally, we wire up and use our HttpClient.
var handler = new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.Zstandard
};
var client = new HttpClient(handler);
var response = await client.GetStringAsync("https://facebook.com");
Console.WriteLine(response.Length);
We are using Facebook here because the server already supports Zstandard.
TLDR
You can utilize Zstandard compression with a HttpClient by wrapping it in a HttpClientHandler.
The code is in my GitHub.
Happy hacking!