c# - HttpClient 抛出 System.ArgumentException : 'windows-1251' is not a supported encoding name

标签 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' 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}

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

最佳答案

获取响应作为 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);

关于c# - HttpClient 抛出 System.ArgumentException : 'windows-1251' is not a supported encoding name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31638035/

相关文章:

java - 阅读 PDF Literal String 解析困境

c# - 无法将类型为 'Windows.UI.Xaml.Controls.Canvas' 的对象转换为类型 'Canvas'

c# - 如何在应用程序最小化或在后台运行时保持计时器运行(C# Windows 10 通用应用程序)

c# - Twitterizer - GetAccessToken() 时出现异常

c# - 将包含与 InvariantCultureIgnoreCase 函数一起使用 c#

c# - 从 Google Apps 帐户访问 GData 日历?

c++ - 使用 Xerces 2.6 序列化汉字

android - 如何以编程方式输入新行?

windows-phone-8 - 如何在 Windows Phone 8.1 (RT) 应用程序中显示动画 GIF?

c# - 如何在 C# 和 Xaml 中将字符串 Url 添加到图像源