Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the encoding of the HttpClient response

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:

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?

like image 599
DreamNet Avatar asked Sep 02 '12 14:09

DreamNet


1 Answers

In case you want a more generic method, following works in my UWP case in case someone has one with Unicode, would be great add the 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);
    }
}
like image 129
Juan Pablo Garcia Coello Avatar answered Sep 30 '22 20:09

Juan Pablo Garcia Coello