I'm building a Windows Store app, but I'm stuck at getting a UTF-8 response from an API.
This is the code:
using (HttpClient client = new HttpClient())
{
Uri url = new Uri(BaseUrl + "/me/lists");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Add("Accept", "application/json");
HttpResponseMessage response = await client.SendRequestAsync(request);
response.EnsureSuccessStatusCode();
string responseString = await response.Content.ReadAsStringAsync();
response.Dispose();
}
The reponseString
always contains strange characters which should be accents like é, and I tried using a stream, but the API I found in some examples don't exist in Windows RT.
Edit: improved code, still same problem.
I like El Marchewko's approach of using an extension, but the code did not work for me. This did:
Solved it like this:
The
HttpClient
doesn't give you a lot of flexibility.You can use a
HttpWebRequest
instead and get the raw bytes from the response usingHttpWebResponse.GetResponseStream()
.Can't comment yet, so I'll have to add my thoughts here.
You could try to use
_client.GetStringAsync(url)
as @cremor suggested, and set your authentication headers using the_client.DefaultRequestHeaders
property. Alternatively, you could also try to use theReadAsByteArrayAsync
method on theresponse.Content
object and useSystem.Text.Encoding
to decode that byte array to a UTF-8 string.Perhaps the problem is that the response is zipped. If the content type is gzip, you will need decompress the response in to a string. Some servers do this to save bandwidth which is normally fine. In .NET Core and probably .NET Framework, this will automatically unzip the response. But this does not work in UWP. This seems like a glaring bug in UWP to me.
This thread gives a clear example of how to decompress the response:
Compression/Decompression string with C#
My approach using an Extension: