我在WPF中有一个应用程序,我使用HttpWebRequest在第三方网站发布登录,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,使用时会得到相同的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。:此用户名和密码只是测试的工作帐户。
答案 0 :(得分:0)
看起来我忘了将Content-Type传递给我的HttpContent。
要修复我的代码,我只需要在StringContent构造函数中添加另一个参数。
HttpContent content = new StringContent(postData, UTF8Encoding.UTF8, "application/x-www-form-urlencoded");