HttpClient抛出System.ArgumentException:'windows-1251'不是受支持的编码名称

时间:2015-07-26 14:22:05

标签: c# character-encoding windows-phone-8.1 httpclient windows-1251

我正在编写WinPhone 8.1应用程序。 代码非常简单,适用于大多数情况:

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

但有时会抛出异常

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

InnerException {System.ArgumentException:'windows-1251'不是   支持的编码名称。参数名称:名称在   System.Globalization.EncodingTable.internalGetCodePageFromName(字符串   姓名)at   System.Globalization.EncodingTable.GetCodePageFromName(String name)
  在   System.Net.Http.HttpContent<> c__DisplayClass1.b__0(任务   任务)System.Exception {System.ArgumentException}

HttpClient是否支持1251编码?如果没有,我该如何避免这个问题呢?或者是目标页面问题?或者我错了什么?

1 个答案:

答案 0 :(得分:6)

获取响应为IBuffer,然后使用.NET编码类进行转换:

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