C# - How to set the encoding of a request using the HttpClient

In this post I demonstrate how you can change the Encoding when using the HTTPClient in C#. To show you how I have created a simple example using PutAsync and StringContent:

var content = new StringContent("{\"someProperty\":\"someValue\"}", Encoding.UTF8, "application/json");
var _httpClient = new HttpClient();
var result = await _httpClient.PutAsync("http://someDomain.com/someUrl", content); //or PostAsync for POST

In the above above I try to PUT a simple JSON object, you can see that I provide the Encoding UTF8. You can provide any of the following Encodings instead:

  • ASCIIEncoding: encodes Unicode characters as single 7-bit ASCII characters.
  • UTF7Encoding: encodes Unicode characters using the UTF-7 encoding.
  • UTF8Encoding: encodes Unicode characters using the UTF-8 encoding
  • UnicodeEncoding: encodes Unicode characters using the UTF-16 encoding. Both little endian and big endian byte orders are supported
  • UTF32Encoding encodes Unicode characters using the UTF-32 encoding. Both little endian and big endian byte orders are supported

That is it, You simply provide another encoding to your (string)Content object which you use for your PutAsync, PostAsync or SendAsync call.