[英]log in to a web page programatically using C#
我想登錄到網頁http://abc/mypage/config/login.aspx並獲取http://abc/mypage/config/config.aspx頁面的html。 我使用過webrequest並嘗試過,但是我總是在獲取登錄頁面html。
WebRequest request = WebRequest.Create("http://abc/mypage/config/login.aspx");
request.Method = "POST";
string postData = "usernameTextBox=myUsername&passwordTextBox=myPassword";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
我對此請求的標頭是:
接受
text / html,application / xhtml + xml,application / xml; q = 0.9, / ; q = 0.8 Accept-Encoding gzip,deflate Accept-Language zh-cn,en; q = 0.5 Connection keep-alive Cookie
ASP.NET_SessionId = nyifft45s13wni45bw0qer3z主機
192.168.174.16參考網址http://abc/mypage/config/login.aspx用戶代理Mozilla / 5.0(Windows NT 6.1; WOW64; rv:39.0)Gecko / 20100101 Firefox / 39.0
我需要通過此頁面登錄並獲取config.aspx頁面的html。
任何幫助將不勝感激。
謝謝。
我猜該網站正在根據您的代碼和aspx頁面使用表單身份驗證。 嘗試添加一個cookie容器
Cookiecontainer cookies = new Cookiecontainer();
//login request to get authentication cookies.
WebRequest request = WebRequest.Create("http://abc/mypage/config/login.aspx");
request.Method = "POST";
request.cookiecontainer = cookies
//your rest of the code
//content request to get what you need
WebRequest request = WebRequest.Create("http://abc/mypage/config/config.aspx");
request.Method = "POST";
request.cookiecontainer = cookies
//same as before
如果通過cookie進行身份驗證,則應該找回所需的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.