0

我在WPF中有一個應用程序,我使用HttpWebRequest在第三方網站發佈登錄,HttpWebRequest.GetResponse工作得很好,並且我得到了我需要的正確的Cookie。HttpClient得不到像HttpWebRequest一樣的CookieContainer

代碼工作正常是:

var cookies = new CookieContainer(); 
string postData = "[email protected]&senha-passaporte=PASS&urlRetorno=http://sportv.globo.com/site/cartola-fc/&usar-sso=true&botaoacessar=acessar"; 
byte[] data = new UTF8Encoding().GetBytes(postData); 

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://loginfree.globo.com/login/438"); 

request.Timeout = 100000; 
request.CookieContainer = cookies; 
request.Method = WebRequestMethods.Http.Post; 
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"; 
request.AllowWriteStreamBuffering = true; 
request.ProtocolVersion = HttpVersion.Version11; 
request.AllowAutoRedirect = true; 
request.ContentType = "application/x-www-form-urlencoded"; 

request.ContentLength = data.Length; 
Stream newStream = request.GetRequestStream(); 
newStream.Write(data, 0, data.Length); 
newStream.Close(); 

HttpWebResponse getResponse = (HttpWebResponse)request.GetResponse(); 

然後,當我試圖端口的Windows 8的商店App這段代碼,使用HttpClient的,我的代碼不返回正確的登錄的Cookie(9塊餅乾代碼以上,僅低於1點的cookie,相同的cookie,我得到的時候使用無效的用戶名或密碼)

var cookies = new CookieContainer(); 

string postData = "[email protected]&senha-passaporte=PASS&urlRetorno=http://sportv.globo.com/site/cartola-fc/&usar-sso=true&botaoacessar=acessar"; 
HttpContent content = new StringContent(postData, UTF8Encoding.UTF8); 

HttpClientHandler handler = new HttpClientHandler(); 
handler.CookieContainer = cookies; 
handler.UseCookies = true; 
handler.AllowAutoRedirect = true; 

var client = new HttpClient(handler); 
client.MaxResponseContentBufferSize = 1024 * 1024; 
client.Timeout = new TimeSpan(1000000000); 
client.DefaultRequestHeaders.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"); 

var response = await client.PostAsync("https://loginfree.globo.com/login/438", content); 

看來,我認爲該HttpClient.PostAsync沒有發出正確的信息的頁面,但我嘗試幾乎所有的東西,我知道並無法弄清楚它是什麼。

PS .:此用戶名和密碼只是測試的工作帳戶。

回答

0

看起來我忘了將Content-Type傳遞給我的HttpContent。

要修復我的代碼,我只需要向StringContent構造函數添加另一個參數。

HttpContent content = new StringContent(postData, UTF8Encoding.UTF8, "application/x-www-form-urlencoded"); 
相關問題