使用httprequest从其他站点登录到aspx页面

时间:2015-12-25 13:54:26

标签: httpwebrequest

使用C#和ASP.NET我想以编程方式填写网页(表单)上的登录详细信息,然后“POST”这些值。我该怎么做?目前我使用的是下面的代码,但它不起作用,它带我在同一页面。

 HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://pcs.d2h.com/");
        req.Method = "GET";
        StreamReader responseReader = new StreamReader(req.GetResponse().GetResponseStream());
        string responseData = responseReader.ReadToEnd();
        responseReader.Close();

        // extract the viewstate value and build out POST data
        string viewState = ExtractViewState(responseData);
        string postData =
              String.Format(
                 "__VIEWSTATE={0}&CenterCPH_tbUsername={1}&CenterCPH_tbPassword={2}&CenterCPH_btnSubmit=Login",
                 viewState, "9115308123", "12345678@A"
              );

        // have a cookie container ready to receive the forms auth cookie
        CookieContainer cookies = new CookieContainer();

        HttpWebRequest req2 = (HttpWebRequest)WebRequest.Create("https://pcs.d2h.com/login.aspx");
        req2.Method = "POST";
        req2.ContentType = "application/x-www-form-urlencoded";
        req2.ContentLength = postData.Length;
        req2.KeepAlive = true;
        req2.CookieContainer = cookies;
        req2.AllowAutoRedirect = false;
        StreamWriter sout = new StreamWriter(req2.GetRequestStream());
        sout.Write(postData);
        sout.Flush();
        sout.Close();
        HttpWebResponse res = (HttpWebResponse)req2.GetResponse();
        StreamReader sr = new StreamReader(res.GetResponseStream());
        string returnvalue = sr.ReadToEnd();
        HttpWebRequest req3 = (HttpWebRequest)WebRequest.Create("https://pcs.d2h.com/Terminals/Default.aspx");
        req3.CookieContainer = cookies;
        res = (HttpWebResponse) req3.GetResponse();
        sr = new StreamReader(res.GetResponseStream());
        returnvalue = sr.ReadToEnd();
        sr.Close();
        return returnvalue;

0 个答案:

没有答案