登录网站并使用 cookie 获取另一个页面的来源 [英] Login to website and use cookie to get source for another page
问题描述
我正在尝试登录 TV Rage 网站并获取我的节目"页面的源代码.我已成功登录(我已检查了来自我的发布请求的响应)但是当我尝试在我的节目"页面上执行获取请求时,我被重定向到登录页面.
I am trying to login to the TV Rage website and get the source code of the My Shows page. I am successfully logging in (I have checked the response from my post request) but then when I try to perform a get request on the My Shows page, I am re-directed to the login page.
这是我用来登录的代码:
This is the code I am using to login:
private string LoginToTvRage()
{
string loginUrl = "http://www.tvrage.com/login.php";
string formParams = string.Format("login_name={0}&login_pass={1}", "xxx", "xxxx");
string cookieHeader;
WebRequest req = WebRequest.Create(loginUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
String responseStream;
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
responseStream = sr.ReadToEnd();
}
return cookieHeader;
}
然后我将 cookieHeader
传递到这个方法中,该方法应该获取 My Shows 页面的源:
I then pass the cookieHeader
into this method which should be getting the source of the My Shows page:
private string GetSourceForMyShowsPage(string cookieHeader)
{
string pageSource;
string getUrl = "http://www.tvrage.com/mytvrage.php?page=myshows";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
return pageSource;
}
我一直在使用上一个问题作为指导,但我'我不知道为什么我的代码不起作用.
I have been using this previous question as a guide but I'm at a loss as to why my code isn't working.
推荐答案
这是使用 WebClient:
class Program
{
static void Main()
{
var shows = GetSourceForMyShowsPage();
Console.WriteLine(shows);
}
static string GetSourceForMyShowsPage()
{
using (var client = new WebClientEx())
{
var values = new NameValueCollection
{
{ "login_name", "xxx" },
{ "login_pass", "xxxx" },
};
// Authenticate
client.UploadValues("http://www.tvrage.com/login.php", values);
// Download desired page
return client.DownloadString("http://www.tvrage.com/mytvrage.php?page=myshows");
}
}
}
/// <summary>
/// A custom WebClient featuring a cookie container
/// </summary>
public class WebClientEx : WebClient
{
public CookieContainer CookieContainer { get; private set; }
public WebClientEx()
{
CookieContainer = new CookieContainer();
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = CookieContainer;
}
return request;
}
}
这篇关于登录网站并使用 cookie 获取另一个页面的来源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!