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.

0

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Well that was far to easy. May i have your permission to edit your anwser and add the handler code?
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...)
Note that SE is also willing to return a "deflate" encoding but it can't be tricked into not compressing the response: stackapps.com/questions/9213/…
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.