我使用此代码从Internet下载字符串
public static async Task<string> DownloadPageAsync(string url)
{
HttpClientHandler handler = new HttpClientHandler {UseDefaultCredentials = true, AllowAutoRedirect = true};
HttpClient client = new HttpClient(handler);
client.MaxResponseContentBufferSize = 196608;
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return responseBody;
}
但它仅适用于UTF8文档。我在哪里设置编码?
答案 0 :(得分:2)
将ReadAsStringAsync更改为ReadAsBufferAsync并使用所需的编码解析结果
var buffer = await response.Content.ReadAsBufferAsync();
byte [] rawBytes = new byte[buffer.Length];
using (var reader = DataReader.FromBuffer(buffer))
{
reader.ReadBytes(rawBytes);
}
var res = Encoding.UTF8.GetString(rawBytes, 0, rawBytes.Length);
答案 1 :(得分:1)
在WinRT中,HttpContent从Headers属性中读取Enconding。如果来自服务器的HTTP响应没有使用编码设置Content-Type标头,它会尝试在流中找到BOM标记,如果没有BOM,它将默认为UTF-8编码。
如果服务器没有发送正确的Content-Type标头,则使用HttpContent.ReadAsStreamAsync()方法并使用您自己的Encoding类实例来正确解码数据。
答案 2 :(得分:0)
设置HttpResponse对象的“ContentEncoding”属性:
值包括:
http://msdn.microsoft.com/en-us/library/system.text.encoding%28v=vs.71%29.aspx
PS:
这本身并不是“地铁” - 只是C#/。Net(尽管.Net 4.x)