Я пытаюсь сделать следующее:
- отправить запрос GET для получения страницы входа (которая запрашивает имя пользователя, пароль и устанавливает файл cookie)
- создайте запрос POST, который отправляет файл cookie из # 1 и тело имени пользователя/пароля (это возвращает Set-Cookie и перенаправляет на целевую страницу веб-сайта для зарегистрированных пользователей)
Моя проблема связана с переадресацией 302. Веб-сервер возвращает 302 с Set-Cookie
, но когда HttpWebRequests выполняет автоматическое перенаправление, он не передает обновленный файл cookie. Чтобы обойти это, я пытаюсь установить .AllowAutoRedirect = false
, сохраняя файлы cookie в CookieCollection, а затем создавая третий HTTP-запрос: GET в окончательное местоположение 302. К сожалению, я не могу установить файлы cookie по этому запросу. Я не уверен, почему, и это сводит меня с ума.
HTTP-запросы по порядку именуются request, postRequest, redirectRequest.
string loginGetUrl = "https://<..>/signin.htm";
string loginPostUrl = "https://<..>/j_acegi_security_check";
string loginRedirectUrl = "https://<..>/centraladmin/poslinks.htm";
string postData = String.Format("j_username={0}&j_password={1}", username, password);
CookieCollection cookies = new CookieCollection();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginGetUrl);
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
//Get the response from the server and save the cookies from the first request..
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
cookies = response.Cookies;
HttpWebRequest postRequest = (HttpWebRequest)WebRequest.Create(loginPostUrl);
postRequest.CookieContainer = new CookieContainer();
// Add the received Cookies from the HTTP Get
postRequest.CookieContainer.Add(cookies);
postRequest.Method = WebRequestMethods.Http.Post;
postRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
postRequest.AllowWriteStreamBuffering = false;
postRequest.ProtocolVersion = HttpVersion.Version11;
postRequest.AllowAutoRedirect = false;
postRequest.ContentType = "application/x-www-form-urlencoded";
byte[] byteArray = Encoding.ASCII.GetBytes(postData);
postRequest.ContentLength = byteArray.Length;
Stream newStream = postRequest.GetRequestStream(); //open connection
newStream.Write(byteArray, 0, byteArray.Length); // Send the data.
newStream.Close();
HttpWebResponse postResponse = (HttpWebResponse)postRequest.GetResponse();
// Save the cookies from the POST login request, then send them on to the redirected URL
cookies = postResponse.Cookies;
HttpWebRequest redirectRequest = (HttpWebRequest)WebRequest.Create(loginRedirectUrl);
redirectRequest.CookieContainer = new CookieContainer();
// add cookies from POST
redirectRequest.CookieContainer.Add(cookies);
HttpWebResponse redirectResponse = (HttpWebResponse)redirectRequest.GetResponse();
В redirectRequest.CookieContainer.Add(cookies);
объект cookie содержит правильный файл cookie. Но когда я смотрю с помощью Fiddler, я вижу только эту информацию:
GET https://<...>/centraladmin/poslinks.htm HTTP/1.1
Host: host:port
Я как бы бьюсь головой о стену в этот момент. Какие-либо предложения? Я ссылаюсь на что-то неправильное? Осторожно, обычно я не пишу код на C#