Login using WebClient or HttpWebRequest

2019-05-16 22:59发布

问题:

Iam having serious problem with login. I cant use WebBrowser class to login to site because WebBrowser is only single thread class. I cannot login with WebClient because I dont have a cookies. Tried to login with HttpWebRequest and Iam guessing I logged succesfully because i got header with: login.success or something like that, but when I retreived source page it returned me login page showing me that Iam not logged.

Iam trying to login to this page: https://lite.betfair.com/Login.do?s=000009z

Url with request: https://lite.betfair.com/SLoginsubmit.do?s=000009z&secure=true&username=user&password=pass

Code:

HttpWebRequest request;
HttpWebResponse response;
CookieContainer cookies;
string url = "https://lite.betfair.com/SLoginsubmit.do?s=000009z&secure=true&username=user&password=pass";
request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = false;
request.CookieContainer = new CookieContainer();
response = (HttpWebResponse)request.GetResponse();
cookies = request.CookieContainer;
response.Close();

request = (HttpWebRequest)WebRequest.Create("https://lite.betfair.com/Events.do?s=000209z");
request.AllowAutoRedirect = false;
request.CookieContainer = cookies;
response = (HttpWebResponse)request.GetResponse(); 

using (Stream s = response.GetResponseStream())
{
     StreamReader sr = new StreamReader(s);
     string line;

     line = sr.ReadToEnd();
}

回答1:

Try : request.CookieContainer = cookies ; instead of cookies = request.CookieContainer;.

HttpWebRequest.CookieContainer



回答2:

Yeah that's what I thought too. You need to set the sessionID from the response of the successful login for all coming requests.