我正在构建一个 Windows 应用商店应用,但我一直无法从 API 获取 UTF-8 响应。
这是代码:
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();
}
reponseString
总是包含奇怪的字符,这些字符应该是像 é 这样的重音符,我尝试使用流,但是我在一些示例中发现的 API 不存在Windows RT。
编辑:改进代码,仍然是同样的问题。
最佳答案
您可以使用@Kiewic 指出的response.Content.ReadAsBufferAsync()
,而不是直接使用response.Content.ReadAsStringAsync()
,如下所示:
var buffer = await response.Content.ReadAsBufferAsync();
var byteArray = buffer.ToArray();
var responseString = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
这在我的案例中有效,我想使用 UTF8 应该可以解决大部分问题。现在想想为什么没有办法使用 ReadAsStringAsync
来做到这一点 :)
关于c# - 在 Windows 应用商店应用程序中使用 httpclient 获取 UTF-8 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22649473/