C#获取页面返回结果(含cookie获取)
程序员文章站
2022-03-25 11:06:09
C#获取页面返回结果(含cookie获取)直接调用方法,传入登录请求地址using System;using System.Net;private string GetCookie(string url){HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); myHttpWebRequest.CookieContainer = new CookieContainer();myHttpWeb...
直接调用方法,传入登录请求地址
using System;
using System.Net;
private string GetCookie(string url){
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
myHttpWebRequest.CookieContainer = new CookieContainer();
myHttpWebRequest.CookieContainer.SetCookies(new Uri(url), "");
HttpWebResponse myresponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
return myresponse.Headers["Set-Cookie"];
}
有时候一些网站的数据请求需要登录后才能获取,这时候可以根据上面的方法获取到cookie保存下来,然后再通过下面的方法请求。
using System.IO;
public string GetHtml(string url, string cookieStr)
{
WebRequest wrt = WebRequest.Create(url);
wrt.Credentials = CredentialCache.DefaultCredentials;
wrt.Headers.Add("Cookie", cookieStr);
WebResponse wrp = wrt.GetResponse();
return new StreamReader(wrp.GetResponseStream(), Encoding.UTF8).ReadToEnd();
}
本文地址:https://blog.csdn.net/LQK976968293/article/details/109235835