0

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.

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449

1 Answers1

1

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);
Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
  • Well that was far to easy. May i have your permission to edit your anwser and add the handler code? – Linda Lawton - DaImTo Aug 27 '22 at 15:21
  • 1
    Sure, go ahead. (Edit: Q already marked as duplicate of the other Q i linked to. I guess this makes editing my answer unnecessary now...) –  Aug 27 '22 at 15:22
  • 1
    Note that SE is also willing to return a "deflate" encoding but it can't be tricked into not compressing the response: https://stackapps.com/questions/9213/why-doesnt-my-xmlhttprequest-call-work-in-excel/9217#9217 – rene Aug 27 '22 at 15:25
  • @TheSkullCaveIsADarkPlace dont worry about it you can still get points for answering the question even if its been duplicated. I searched for everything, I thought it was en encoding issue. Never occurred to me it was compressed. – Linda Lawton - DaImTo Aug 27 '22 at 15:36