我一直试图让它工作几个小时而收效甚微。从第一次请求后的源代码我可以看到登录成功,但使用cookie访问其他请求登录信息。
以下是我尝试访问的网站:http://gpro.net/
以下是我正在使用的代码: string formUrl =“http://gpro.net/pl/Login.asp?langCode=pl&Redirect=gpro.asp”; //注意:这是表单POST的URL,而不是表单的URL(您可以在HTML的表单标签的“action”属性中找到它) string formParams =“textLogin = user& textPassword = pass& Logon = Login& LogonFake = Sign + in”;
string strResponse;
HttpWebRequest requestLogin = (HttpWebRequest)WebRequest.Create(formUrl);
requestLogin.Method = "POST";
requestLogin.CookieContainer = cookieJar;
requestLogin.ContentType = "application/x-www-form-urlencoded";
requestLogin.ContentLength = formParams.Length;
StreamWriter stOut = new StreamWriter(requestLogin.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(formParams);
stOut.Close();
HttpWebResponse responseLogin = (HttpWebResponse)requestLogin.GetResponse();
StreamReader stIn = new StreamReader(responseLogin.GetResponseStream());
strResponse = stIn.ReadToEnd();
stIn.Close();
sb.Append(strResponse);
sb.AppendLine();
sb.AppendLine();
sb.AppendLine();
//Add cookies to CookieJar (Cookie Container)
foreach (Cookie cookie in responseLogin.Cookies)
{
cookieJar.Add(new Cookie(cookie.Name.Trim(), cookie.Value.Trim(), cookie.Path, cookie.Domain));
sb.AppendLine(cookie.Name.ToString() + Environment.NewLine + cookie.Value.ToString() + Environment.NewLine + cookie.Path.ToString() + Environment.NewLine + cookie.Domain.ToString());
}
//Grab the cookie we just got back for this specifc page
string cookies = cookieJar.GetCookieHeader(requestLogin.RequestUri);
//put it back in the cookie container for the whole server
cookieJar.SetCookies(new Uri("http://www.gpro.net/"), cookies);
string testResults = string.Empty;
HttpWebRequest runTest = (HttpWebRequest)WebRequest.Create("http://www.gpro.net/pl/RaceAnalysis.asp");
runTest.Referer = "http://gpro.net/pl/gpro.asp";
runTest.CookieContainer = cookieJar;
//runTest.Method = "POST";
//runTest.ContentType = "application/x-www-form-urlencoded";
//StreamWriter stOut2 = new StreamWriter(runTest.GetRequestStream(), System.Text.Encoding.ASCII);
//stOut2.Write(formParams);
//stOut2.Close();
StreamReader stIn2 = new StreamReader(runTest.GetResponse().GetResponseStream());
testResults = stIn2.ReadToEnd();
stIn2.Close();
sb.Append(testResults);
e.Result = sb.ToString();
答案 0 :(得分:0)
我发现上面的代码有什么问题,并且堆栈溢出中发布的每个类似的代码(我已经尝试了所有标记为工作)。当我使用浏览器重定向进行日志记录工作正常时,但使用上述方法我的请求被重定向到相同的地址,但没有www前缀。这产生了两个不同的cookie集合。我从解决登录问题的每个请求中删除了www前缀。