[英]Programatiically login to a website that uses IIS authentication
大家好,我正在嘗試以編程方式登錄網站。我已經在處理此問題,但是這是一個php頁面,我使用了下面的代碼(在Stack Overflow上的某些位置找到了)來登錄它,效果很好。
private static string GetDataFromPHP(string formUrl, string getUrl, string username, string password, out bool status)
{
try
{
string formParams = string.Format("access_login={0}&access_password={1}", username, 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"];
string pageSource;
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
status = true;
return pageSource;
}
catch (System.Exception ex)
{
status = false;
return string.Empty;
}
}
其中access_login和access_password是接受憑據的輸入框的名稱,我不知道如何針對iis登錄提示實現它,如下所示。
如果您可以通過瀏覽器登錄並使用Fiddler攔截請求,則可以使用Fiddler附加組件的Request-To-Code生成將執行請求的C#代碼。 生成的代碼至少可能是您入門的好地方。
在類似情況下,我已經成功地將Fiddler與Request-To-Code一起使用。
嘗試使用HttpWebRequest類和NetworkCredentials類來完成此操作。
這是一段代碼,可以幫助您朝正確的方向發展。
// Create Request
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://www.yourdomain/whatever");
// Create Client
WebClient client = new WebClient();
// Assign Credentials
client.Credentials = new NetworkCredential("user", "password");
// Grab Data
string htmlCode = client.DownloadString("http://www.yourdomain/whatever");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.