Search code examples
c#character-encodingwindows-phone-8.1httpclientwindows-1251

HttpClient throws System.ArgumentException: 'windows-1251' is not a supported encoding name


I am writing WinPhone 8.1 app. Code is very simple and works in most cases:

string htmlContent;
using (var client = new HttpClient())
{
    htmlContent = await client.GetStringAsync(GenerateUri());
}
_htmlDocument.LoadHtml(htmlContent);

But sometimes exception is thrown at

htmlContent = await client.GetStringAsync(GenerateUri());

InnerException {System.ArgumentException: 'windows-1251' is not a supported encoding name. Parameter name: name at System.Globalization.EncodingTable.internalGetCodePageFromName(String name) at System.Globalization.EncodingTable.GetCodePageFromName(String name)
at System.Net.Http.HttpContent.<>c__DisplayClass1.b__0(Task task)} System.Exception {System.ArgumentException}

Does HttpClient support 1251 encoding? And if it doesn't, how can I avoid this problem? Or is it target page problem? Or am I wrong in something?


Solution

  • Get response as IBuffer and then convert using .NET encoding classes:

    HttpClient client = new HttpClient();
    HttpResponseMessage response = await client.GetAsync(uri);
    IBuffer buffer = await response.Content.ReadAsBufferAsync();
    byte[] bytes = buffer.ToArray();
    
    Encoding encoding = Encoding.GetEncoding("windows-1251");
    string responseString = encoding.GetString(bytes, 0, bytes.Length);