c# - 在 Windows 应用商店应用程序中使用 httpclient 获取 UTF-8 响应

标签 c# .net utf-8 character-encoding windows-runtime

我正在构建一个 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/

相关文章:

c# - 我如何强制禁用元素的 wpf 窗口/控件刷新

c# - 为什么 RSAParameters Modulus 不等于 P 和 Q 的乘积?

c# - 检索 SQL 表中的列数 - C#

php - 循环遍历 MySQL 数据库,使用 UTF-8 版本更改撇号

firefox - Firefox 中的 UTF-8 问题 - 响应 header 覆盖元标记?

c# - 如何在安装项目 (C#) 的应用程序数据中安装文件

C# 字符串与字符串, boolean 与 boolean 值

c# - WPF FlowDocument 仅打印到小区域

c# - 在 C# 中防止 SQL 注入(inject) asp.net

c - 如何在 C 中将 UTF-8 字符转换为二进制