How to change the encoding of the HttpClient response(如何更改 HttpClient 响应的编码)
问题描述
我正在尝试学习使用 VS2012 及其 Async Await 关键字的异步编程.这就是我写这段代码的原因:
I'm trying to learn about Async programming using VS2012 and its Async Await keyword. That is why i wrote this piece of code:
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
string get = await GetResultsAsync("http://saskir.medinet.se");
resultsTextBox.Text = get;
}
private async Task<string> GetResultsAsync(string uri)
{
HttpClient client = new HttpClient();
return await client.GetStringAsync(uri);
}
问题是当我尝试调试应用程序时,它给了我一条错误消息:
The problem is that when i try to debug the application, it gives me an error with this message:
ContentType 中提供的字符集无效.无法使用无效字符集将内容读取为字符串.
The character set provided in ContentType is invalid. Cannot read content as string using an invalid character set.
我猜这是因为该网站有一些瑞典字符,但我找不到如何更改响应的编码.有人可以指导我吗?
I guess this is because the website have some Swedish char, but i can't find how to change the encoding of the response. Anyone can guide me plz?
推荐答案
您可能需要检查编码选项并获得正确的选项.否则,此代码应该让您继续响应.
You may have to check the encoding options and get the correct one. Otherwise, this code should get you going with the response.
private async Task<string> GetResultsAsync(string uri)
{
var client = new HttpClient();
var response = await client.GetByteArrayAsync(uri);
var responseString = Encoding.Unicode.GetString(response, 0, response.Length - 1);
return responseString;
}
这篇关于如何更改 HttpClient 响应的编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何更改 HttpClient 响应的编码
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01