I'm writting application in .NET
, where I need to get data from some api.
I tried to use different reading method e.g ReadAsStringAsync()
, I tried to convert them in UTF-8
, I set mediaType text/plain, I tried to convert to JSON
, but it raised an error during parsing.
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
byte[] responded;
HttpResponseMessage response = await client.GetAsync(path);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
if (response.IsSuccessStatusCode)
{
response.Content.ReadAsByteArrayAsync().Wait();
responded = response.Content.ReadAsByteArrayAsync().Result;
var responseString = Encoding.UTF8.GetString(responded, 0, responded.Length);
Console.WriteLine("\n " +responseString);
}
I get respond:
?0E?%?}S??WDJpq?%)X??}???s????A???BK?X?}?k
but it's not what I expect:
{"items:[{"has_synonyms":true,"is_moderator_only":false,"is_required":false,"count":9452,"name":"tags"}],"has_more":false,"quota_max":300,"quota_remaining":296}
I didn't realize, that response is in gzip format.. I made changes:
Stream responded;
HttpResponseMessage response = await client.GetAsync(new Uri(path));
if (response.IsSuccessStatusCode)
{
response.Content.ReadAsStringAsync().Wait();
responded = response.Content.ReadAsStreamAsync().Result;
Stream decompressed = new GZipStream(responded, CompressionMode.Decompress);
StreamReader objReader = new StreamReader(decompressed, Encoding.UTF8);
string sLine;
sLine = objReader.ReadToEnd();
}
and it works properly.