Getting an UTF-8 response with httpclient in Windo

2020-02-10 18:08发布

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.

7条回答
smile是对你的礼貌
2楼-- · 2020-02-10 19:09

Instead of using response.Content.ReadAsStringAsync() directly you could use response.Content.ReadAsBufferAsync() pointed by @Kiewic as follows:

var buffer = await response.Content.ReadAsBufferAsync();
var byteArray = buffer.ToArray();
var responseString = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);

This is working in my case and I guess that using UTF8 should solve most of the issues. Now go figure why there is no way to do this using ReadAsStringAsync :)

查看更多
登录 后发表回答