Webclient UploadValues 编码
Webclient UploadValues encoding
我在 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,所以我做了一个 class:
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);
我在 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,所以我做了一个 class:
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);