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 响应的编码
基础教程推荐
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
