17

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?

PoLáKoSz
  • 355
  • 1
  • 6
  • 7
DreamNet
  • 627
  • 3
  • 8
  • 24

3 Answers3

33

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;
}
PoLáKoSz
  • 355
  • 1
  • 6
  • 7
Sandeep G B
  • 3,957
  • 4
  • 26
  • 43
  • Thanks for the help, it solved the problem after just changing Unicode to UTF8. But i really didn't get it why my initial code was not working. Any idea why? – DreamNet Sep 02 '12 at 16:58
  • 1
    In your code, "GetStringAsync" was using default encoding and trying to get the string which was failing. With "GetByteArrayAsync", result is in the form of byte[] which doesn't result in encoding issues. – Sandeep G B Sep 02 '12 at 17:28
7

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);
    }
}
PoLáKoSz
  • 355
  • 1
  • 6
  • 7
Juan Pablo Garcia Coello
  • 3,192
  • 1
  • 23
  • 33
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();
A.J.Bauer
  • 2,803
  • 1
  • 26
  • 35