Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

HttpClient get Not returning json

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading