C#HttpWebRequest与cookies一起访问网页GET

C#访问网页的方式有很多,通常使用网络客户端(WebClient)、网络浏览器(WebBrowser)或HttpWebRequest。 前两个相对简单,而后一个功能更强,便于我们伪造访问痕迹。

以下是HttpWebRequest使用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;

}

转载请注明出处:C#HttpWebRequest与cookies一起访问网页GET
本文链接:https://www.axdzc.com/blog/chwcg

 

 

评论0

请先

1.即日起暂时取消网站QQ登录,之前用QQ登录的会员请联系客服绑定邮箱或改为密码登录。 2.交流社区已上线,会员如需交流请移动至交流社区发帖。
没有账号? 忘记密码?