我对使用C#相对较新,并且有一个应用程序可以在网站上读取部分源代码。这一切都有效;但问题是有问题的页面要求用户登录才能访问此源代码。我的程序需要最初将用户登录到网站的方式 - 完成后,我将能够访问和阅读源代码。
需要登录的网站是: mmoinn.com/index.do?PageModule=UsersLogin
我一整天都在搜索如何做到这一点并尝试过例子,但没有运气。
提前致谢
答案 0 :(得分:102)
您可以继续使用WebClient进行POST(而不是GET,这是您目前正在使用DownloadString的HTTP verb),但我认为您会发现更容易使用(略微)更低 - 级别WebRequest和WebResponse。
这有两个部分 - 第一部分是发布登录表单,第二部分是恢复“Set-cookie”标题,并将其作为“Cookie”发送回服务器以及您的GET请求。从现在开始,服务器将使用此cookie来识别您(假设它使用基于cookie的身份验证,我非常有信心,因为该页面返回包含“PHPSESSID”的Set-cookie标头)。
发布到登录表单
表单帖子很容易模拟,只是格式化帖子数据的情况如下:
field1=value1&field2=value2
使用我从Scott Hanselman改编的WebRequest和代码,以下是将表单数据发布到登录表单的方式:
string formUrl = "http://www.mmoinn.com/index.do?PageModule=UsersAction&Action=UsersLogin"; // NOTE: This is the URL the form POSTs to, not the URL of the form (you can find this in the "action" attribute of the HTML's form tag
string formParams = string.Format("email_address={0}&password={1}", "your email", "your password");
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
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"];
以下是您应在登录表单的Set-cookie标头中看到的内容示例:
PHPSESSID=c4812cffcf2c45e0357a5a93c137642e; path=/; domain=.mmoinn.com,wowmine_referer=directenter; path=/; domain=.mmoinn.com,lang=en; path=/;domain=.mmoinn.com,adt_usertype=other,adt_host=-
获取登录表单后面的页面
现在,您可以对需要登录的页面执行GET请求。
string pageSource;
string getUrl = "the url of the page behind the login";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
修改强>
如果您需要查看第一个POST的结果,可以恢复它返回的HTML:
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
将其直接放在cookieHeader = resp.Headers["Set-cookie"];
下面,然后检查pageSource中保存的字符串。
答案 1 :(得分:33)
通过创建一个派生自WebClient的类,重写其GetWebRequest方法并在其上设置CookieContainer对象,可以简化一些事情。如果您始终设置相同的CookieContainer实例,则将自动为您处理Cookie管理。
但是在发送之前获取HttpWebRequest的唯一方法是从WebClient继承并覆盖该方法。
public class CookieAwareWebClient : WebClient
{
private CookieContainer cookie = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = cookie;
}
return request;
}
}
var client = new CookieAwareWebClient();
client.BaseAddress = @"https://www.site.com/any/base/url/";
var loginData = new NameValueCollection();
loginData.Add("login", "YourLogin");
loginData.Add("password", "YourPassword");
client.UploadValues("login.php", "POST", loginData);
//Now you are logged in and can request pages
string htmlSource = client.DownloadString("index.php");
答案 2 :(得分:7)
Matthew Brindley,您的代码对我需要的某个网站(登录)非常有用,但我需要更改为HttpWebRequest
和HttpWebResponse
,否则我会得到 404 Bad从远程服务器请求。另外,我想使用您的代码分享我的解决方法,并且我尝试登录基于moodle的网站,但它在您的步骤“ GETting the page在登录表单后面“因为当成功 POSTing 登录时,标题'Set-Cookie'
没有返回任何内容,尽管其他网站都没有。
所以我认为我们需要为下一个请求存储cookie,所以我添加了这个。
到“发布到登录表单”代码块:
var cookies = new CookieContainer();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(formUrl);
req.CookieContainer = cookies;
并且“获取登录表单后面的页面”:
HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl);
getRequest.CookieContainer = new CookieContainer();
getRequest.CookieContainer.Add(resp.Cookies);
getRequest.Headers.Add("Cookie", cookieHeader);
这样做,让我登录我并获取“登录页面”的源代码(基于网站的moodle)我知道这是对CookieContainer
和HTTPCookies的模糊使用,因为我们可能先询问是否在将请求发送到服务器之前保存了先前的一组cookie。无论如何,这都没有问题,但是这里有一个很好的信息,可以通过示例项目和教程来了解WebRequest
和WebResponse
:
Retrieving HTTP content in .NET
How to use HttpWebRequest and HttpWebResponse in .NET
答案 3 :(得分:2)
有时,关闭AllowAutoRedirect
并设置登录POST
和页面GET
请求相同的用户代理可能会有所帮助。
request.UserAgent = userAgent;
request.AllowAutoRedirect = false;