HttpClient get Not returning json

154 views Asked by At

This rest endpoint https://api.stackexchange.com/2.3/questions?order=desc&sort=activity&site=stackoverflow returns a json response when i place it in a web browser.

Yet when i run the following

public class StackApi
{
    private const string BaseURI = "https://api.stackexchange.com/";
    private HttpClient _httpClient;

    public StackApi()
    {
        _httpClient=  new HttpClient();
        _httpClient.BaseAddress = new Uri(BaseURI);
        _httpClient.DefaultRequestHeaders.Accept.Clear();
        _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public async Task<string> GetQuestions()
    {
        var responseMessage  =
            await _httpClient.GetAsync("2.3/questions?order=desc&sort=activity&site=stackoverflow");

        if (responseMessage.IsSuccessStatusCode)
        {
            var responseString = await responseMessage.Content.ReadAsStringAsync();
            return responseString;
        }

        return string.Empty;
    }
}

The response is not in json it apears to be encoded somehow

enter image description here

The content type appears to be json

enter image description here

More then a little confused as to why this is not a json response.

1

There are 1 answers

4
AudioBubble On BEST ANSWER

Look at the content-encoding header of the response you got. It is gzip (check the long-ish header string in your screenshot at the far right side). To automatically let HttpClient uncompress it, see this answer to a related question: https://stackoverflow.com/a/27327208

var handler = new HttpClientHandler()
    {
        AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
    };        
    
    _httpClient=  new HttpClient(handler);