How to change the encoding of an HttpClient response

I am trying to learn about asynchronous programming using VS2012 and its Async Await keyword. This 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, I get an error message:

The character set provided in ContentType is not valid. Cannot read contents as a string using the wrong character set.

I think this is because there is some Swedish character on the site, but I can not find how to change the response encoding. Can anyone direct me plz?

+8
source share
3 answers

You may need to check the encoding parameters and get the correct one. Otherwise, this code should give you an answer.

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;
}
+19

, UWP, - Unicode, :

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

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();
0
source

All Articles