我試圖做到以下幾點:HttpWebReponse Cookie不能設置爲重定向
- 發送GET請求來獲取一個登錄頁面(即提示提供用戶名,密碼,並設置一個cookie)
- 構建一個POST請求,從#1發送cookie和一個用戶名/密碼的主體(這將返回一個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。但是當我和小提琴手一起看時,我只看到這個信息:
GET https://<...>/centraladmin/poslinks.htm HTTP/1.1
Host: host:port
我有點在牆上敲打我的頭。有什麼建議麼?我指的是錯誤的嗎?請注意,我通常不會編寫C#代碼
我也處於類似的情況,像tommy_o。但是我正在使用的應用程序,我們使用.NET 4.0。任何幫助或指導,非常感謝。 – Aishu