繁体   English   中英

使用C#以编程方式登录到网页

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM