当返回HttpResponseMessage对象后,判断responseMessage中的HttpHeader是否包含编码,如果没有,就指定编码即可。代码如下:
var contentType = message.Content.Headers.ContentType; if (string.IsNullOrEmpty(contentType.CharSet)) { contentType.CharSet = "utf-8"; }
完整的PostAsync()代码如下:
HttpResponseMessage message = await App.Client.PostAsync(new Uri("http://neihanshe.cn/login", UriKind.Absolute), content);
var contentType = message.Content.Headers.ContentType;
if (string.IsNullOrEmpty(contentType.CharSet))
{
contentType.CharSet = "utf-8";
}
Debug.WriteLine(message.Content);
有的时候如果要更精确的话还需要从Html页面中获取charset信息,封装一个通用的工具方法如下:
private async Task<string> getCharSetAsync(HttpContent httpContent)
{
var charset = httpContent.Headers.ContentType.CharSet;
if (!string.IsNullOrEmpty(charset))
return charset;
var content = await httpContent.ReadAsStringAsync();
var match = Regex.Match(content, @"charset=(?<charset>.+?)""", RegexOptions.IgnoreCase);
if (!match.Success)
return charset;
return match.Groups["charset"].Value;
}