1
我需要登录到一个网站,从各种页面登录时下载源代码。我能够做到这一点很容易,当使用Windows窗体WebBrowser类,但这不是合适的,我需要能够通过WebRequest或其他人做到这一点。不幸的是,它不喜欢我如何处理cookie。C#登录网站和使用WebRequest下载源代码 - 问题与Cookie
我使用以下代码并获得以下响应:{“w_id”:“LoginForm2_6”,“message”:“请在您的浏览器中启用cookie以便登录。”,“success”:0, “showLink”:false}
string url2 = "%2Fapp%2Futils%2Flogin_form%2Fredirect%2Fhome";
string login = "username";
string password = "password";
string w_id = "LoginForm2_6";
string loginurl = "http://loginurl.com";
string cookieHeader;
WebRequest req = WebRequest.Create(loginurl);
req.Proxy = WebRequest.DefaultWebProxy;
req.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
req.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
req.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
req.Method = "POST";
string postData = string.Format("w_id={2}&login={0}&password={1}&url2={3}", login, password, w_id, url2);
byte[] bytes = Encoding.ASCII.GetBytes(postData);
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 pageSource = "";
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
richTextBox1.Text = pageSource;
如果有人可以告诉我我哪里出错了,那将不胜感激。
此外,为了让你知道,如果我用web浏览器类下面,它工作在精细:
b.Navigate(fullurl, "", enc.GetBytes(postData), "Content-Type: application/x-www-form-urlencoded\r\n");