Webclient UploadValues编码

时间:2015-10-20 19:38:53

标签: c# .net encoding webclient

我在URL中创建POST并将响应作为字符串获取,如下所示:

var responseBytes = client.UploadValues("www.example.com", requestData.Body);
var html = Encoding.UTF8.GetString(responseBytes, 0, responseBytes.Length);
html = HttpUtility.HtmlDecode(html);

我创建了一个WebClient子项来接受cookie,所以我创建了这个类:

 public class CookieWebClient : WebClient
{
    public CookieContainer CookieContainer { get; }

    public CookieWebClient()
    {
        CookieContainer = new CookieContainer();
        Encoding = Encoding.UTF8;
    }

    public CookieWebClient(CookieContainer cookieContainer)
    {
        CookieContainer = cookieContainer;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address) as HttpWebRequest;
        if (request == null) return base.GetWebRequest(address);
        request.CookieContainer = CookieContainer;
        return request;
    }
}

如您所见,我在构造函数中设置了编码。但是,当我获得html属性时,某些字符会变为:� necess�rio,它应该是É necessário

任何想法都错了吗?

1 个答案:

答案 0 :(得分:0)

你正在使用“拉丁语1”字符(葡萄牙语,也许?),所以你应该选择:

var html = Encoding.GetEncoding("ISO-8859-1")
                   .GetString  (responseBytes, 0, responseBytes.Length);