我在 WPF 中有一个应用程序,我使用 HttpWebRequest 在 3rd 方网站上发布登录信息,HttpWebRequest.GetResponse 工作得很好,我得到了我需要的正确 cookie。
工作正常的代码是:
var cookies = new CookieContainer();
string postData = "login-passaporte=email@yahoo.com.br&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();
然后,当我尝试使用 HttpClient 将此代码移植到 Windows 8 商店应用程序时,我的代码不会返回正确的记录 cookie(上面的代码中有 9 个 cookie,下面只有 1 个 cookie,与使用无效用户名或密码)
var cookies = new CookieContainer();
string postData = "login-passaporte=email@yahoo.com.br&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.:这个用户名和密码只是一个用于测试的工作帐户。