Getting an UTF-8 response with httpclient in Windows Store apps(在 Windows 应用商店应用程序中使用 httpclient 获取 UTF-8 响应)
问题描述
我正在构建一个 Windows 应用商店应用,但我一直无法从 API 获得 UTF-8 响应.
I'm building a Windows Store app, but I'm stuck at getting a UTF-8 response from an API.
这是代码:
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.
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.
改进的代码,仍然是同样的问题.
improved code, still same problem.
推荐答案
你可以使用 response.Content.ReadAsBufferAsync()
而不是直接使用 response.Content.ReadAsStringAsync()
@Kiewic 指向的代码> 如下:
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);
这在我的情况下有效,我想使用 UTF8 应该可以解决大部分问题.现在想想为什么没有办法使用 ReadAsStringAsync
来做到这一点:)
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
:)
这篇关于在 Windows 应用商店应用程序中使用 httpclient 获取 UTF-8 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Windows 应用商店应用程序中使用 httpclient 获取


基础教程推荐
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01