如何更改 HttpClient 响应的编码 [英] How to change the encoding of the HttpClient response

查看:23
本文介绍了如何更改 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 响应的编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆