HttpWebRequest獲取頁面內容時,得到“遠程服務器返回錯誤: (403) 已禁止。”
找了些解決方案,補充UserAgent
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; QQWubi 133; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; CIBA; InfoPath.2)";
添加后成功解決,但是不久仍出現此問題,又添加CookieContainer
httpReq.CookieContainer = new CookieContainer();
再次解決。
在我遇到的這種情況下,通過這兩行代碼解決了“遠程服務器返回錯誤: (403) 已禁止。”的問題。
其實還有個問題,返回內容亂碼時,可能是Encoding或網站使用了gzip進行壓縮,而HttpResponse默認不處理。以下代碼嘗試解決。
HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
Stream respStream = httpResp.GetResponseStream();
StreamReader respStreamReader = new StreamReader(new GZipStream(respStream, CompressionMode.Decompress), System.Text.Encoding.UTF8);