我一直试图让它工作几个小时,但收效甚微。从第一次请求后的源代码中,我可以看到登录成功,但使用 cookie 访问其他人不断询问登录信息。
这是我要访问的网站:http: //gpro.net/
这是我正在使用的代码: string formUrl = "http://gpro.net/pl/Login.asp?langCode=pl&Redirect=gpro.asp"; // 注意:这是表单发布到的 URL,而不是表单的 URL(您可以在 HTML 表单标签字符串的“action”属性中找到它 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();