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

This post demonstrates how you can change the Encoding when using the HTTPClient in C#. You can do this by setting the encoding on the StringContent object for your requests with a body, below is a simple example:

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 we PUT a simple JSON object, we provide the Encoding UTF8 for the StringContent object which is later use in a PutAsync call. StringContent allows you to set the body and its associated headers for a request. 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

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