Search code examples
c#jsondotnet-httpclient

HTTPClient Post Response is Unreadable


I am sending a response in postman that works correctly. When i attempt to recreate it in c# the response indicates success but the content is illegible.

\u001f�\b\0\0\0\0\0\0\0uT�s�0\u0010~�_���v���O\u0017\u0011�Z�\fPo�n:�\bk�+$\u000e�^���\u0011J\u00144�i�v��v��...

I am creating the request as follows:

HttpClient client = new HttpClient();
var tokenRequest = new HttpRequestMessage(HttpMethod.Post, url);
tokenRequest.Content = new StringContent(JsonConvert.SerializeObject(new object {});
var tokenResponse = await client.SendAsync(tokenRequest);
tokenResponse.EnsureSuccessStatusCode();
var content = await tokenResponse.Content.ReadAsStringAsync();

The response in postman looks like:

{
    "token": "sometoken",
    "type": "Bearer",
    ...
}

Solution

  • Enable automatic decompression for the HttpClient, for example:

    HttpClient client = new HttpClient(new SocketsHttpHandler()
    {
        AutomaticDecompression = DecompressionMethods.GZip // or All
    });
    

    Also check out:

    for best practices working with the HttpClient