Webclient UploadValues encoding
本文关键字:encoding UploadValues Webclient | 更新日期: 2023-09-27 18:18:44
我在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
。你知道怎么回事吗?
您正在使用"Latin 1"字符(也许是葡萄牙语?),所以您应该使用:
var html = Encoding.GetEncoding("ISO-8859-1")
.GetString (responseBytes, 0, responseBytes.Length);