Har*_*ith 3 c# httpclient character-encoding windows-phone-8.1 windows-1251
我正在写WinPhone 8.1应用程序.代码非常简单,适用于大多数情况:
string htmlContent;
using (var client = new HttpClient())
{
htmlContent = await client.GetStringAsync(GenerateUri());
}
_htmlDocument.LoadHtml(htmlContent);
Run Code Online (Sandbox Code Playgroud)
但有时会抛出异常
htmlContent = await client.GetStringAsync(GenerateUri());
Run Code Online (Sandbox Code Playgroud)
InnerException {System.ArgumentException:'windows-1251'不是受支持的编码名称.参数名称:System.Globalization.EncodingTable.internalGetCodePageFromName(String name)的名称,
位于System.Net.Http.HttpContent的System.Globalization.EncodingTable.GetCodePageFromName(String name).<> c__DisplayClass1.b__0(任务任务)} 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);
Run Code Online (Sandbox Code Playgroud)