14

我正在尝试使用 VS2012 及其 Async Await 关键字来学习异步编程。这就是我写这段代码的原因:

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);
}

问题是,当我尝试调试应用程序时,它给了我一条错误消息:

ContentType 中提供的字符集无效。无法使用无效字符集将内容读取为字符串。

我想这是因为该网站有一些瑞典字符,但我找不到如何更改响应的编码。有人可以指导我吗?

4

3 回答 3

28

您可能必须检查编码选项并获得正确的选项。否则,此代码应该让您继续响应。

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;
}
于 2012-09-02T16:46:08.807 回答
6

如果你想要一个更通用的方法,在我的 UWP 案例中,如果有人有一个 Unicode,那么添加 if 会很好:

var response = await httpclient.GetAsync(urisource);

if (checkencoding)
{
    var contenttype = response.Content.Headers.First(h => h.Key.Equals("Content-Type"));
    var rawencoding = contenttype.Value.First();

    if (rawencoding.Contains("utf8") || rawencoding.Contains("UTF-8"))
    {
        var bytes = await response.Content.ReadAsByteArrayAsync();
        return Encoding.UTF8.GetString(bytes);
    }
}
于 2016-11-19T08:05:59.570 回答
0

WinRT 8.1 C#

using Windows.Storage.Streams;
using System.Text;
using Windows.Web.Http;

// in some async function

Uri uri = new Uri("http://something" + query);
HttpClient httpClient = new HttpClient();

IBuffer buffer = await httpClient.GetBufferAsync(uri);
string response = Encoding.UTF8.GetString(buffer.ToArray(), 0, (int)(buffer.Length- 1));

// parse here

httpClient.Dispose();
于 2015-07-24T19:41:35.040 回答