让代码更简单

C#HttpWebRequest带cookies访问网页GET

重要:本文最后更新于2018-05-04 09:16:10,某些文章具有时效性,若有错误或已失效,请在下方留言或联系代码狗

C#访问网页的办法很多,一般使用WebClient、WebBrowser或者HttpWebRequest。前两种比较简单,后者功能更多,方便我们伪造访问痕迹。

下面是HttpWebRequest带cookies访问百度首页的方法,访问结果如下图所示:

C#HttpWebRequest带cookies访问网页

C#HttpWebRequest带cookies访问网页

从上图红线框中可以看出,带上cookies可以达到模拟登陆的效果,顺便模拟了浏览器,下面是C#代码。

复制
/// <summary>
 /// 获取页面html
 /// </summary>
 /// <param name="uri">访问url</param>
 /// <param name="refererUri">来源url</param>
 /// <param name="encodingName">编码名称 例如:gb2312</param>
 /// <returns></returns>
 public string Get(string uri, string refererUri, string encodingName)
 {
 string html = string.Empty;
 CookieContainer cookieContainer = new CookieContainer();
 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
 cookieContainer.Add(new Cookie("BAIDUID", "67017F5C6A5EE8351192F7D34E7A221E:FG=1", "", "www.baidu.com"));
 cookieContainer.Add(new Cookie("PSTM", "1523879243", "", "www.baidu.com"));
 cookieContainer.Add(new Cookie("BIDUPSID", "A29EA919049CED566C183C7ED175C6AB", "", "www.baidu.com"));
 cookieContainer.Add(new Cookie("BD_UPN", "1a314353", "", "www.baidu.com"));
 cookieContainer.Add(new Cookie("BDUSS", "1F4Wk1EUUxEWkNEZS1lUWdSNkFWOW5IbThoYXNYcktMWmhmRkE5MkxvQU9Jd0piQVFBQUFBJCQAAAAAAAAAAAEAAAD9qTIYw867wzGw19K5AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA6W2loOltpaY", "", "www.baidu.com"));
 request.ContentType = "text/html;charset=" + encodingName;
 request.Method = "Get";
 request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.5221.400 QQBrowser/10.0.1125.400";
 request.CookieContainer = cookieContainer;

if (!string.IsNullOrEmpty(refererUri))
 request.Referer = refererUri;

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
 {
 using (Stream streamResponse = response.GetResponseStream())
 {
 using (StreamReader streamResponseReader = new StreamReader(streamResponse, Encoding.GetEncoding(encodingName)))
 {
 html = streamResponseReader.ReadToEnd();
 }
 }
 }

return html;

}

感觉很棒!可以赞赏支持我哟~

7 打赏

评论 (3)

登录后评论
您好,看到您的网站,我希望与您友情链接,我的网站:www.yuedutop.cn 目前有一点流量,同意的话联系我吧!397423577@qq.com
抱歉,内容不相关。
本站已开通投稿,欢迎博主支持!(采纳后提供版权保护,开通作者专栏)
QQ咨询 邮件咨询 狗哥推荐