【问题标题】:C# Metro HttpClient not receiving cookie on PostAsyncC# Metro HttpClient 未在 PostAsync 上接收 cookie
【发布时间】:2012-07-26 00:34:39
【问题描述】:

我正在尝试使用 .NET 4.5 HttpClient 登录网站并接收 cookie。我在离开之前就中断了尝试并检查 CookieContainer 并且它不包含任何 cookie。不过,响应会发回 200 状态。

private async void Login(string username, string password)
{
    try
    {
        Uri address = new Uri(@"http://website.com/login.php");
        CookieContainer cookieJar = new CookieContainer();
        HttpClientHandler handler = new HttpClientHandler()
        {
            CookieContainer = cookieJar
        };
        handler.UseCookies = true;
        handler.UseDefaultCredentials = false;
        HttpClient client = new HttpClient(handler as HttpMessageHandler)
        {
            BaseAddress = address
        };

        HttpContent content = new StringContent(string.Format("username={0}&password={1}&login=Login&keeplogged=1", username, password));
        HttpResponseMessage response = await client.PostAsync(client.BaseAddress, content);
    }

我不知道为什么这不起作用。当我尝试 .NET 4 样式时,它工作正常。

【问题讨论】:

  • 顺便说一句:使用 FormUrlEncodedContent 而不是 StringContent 和 string.Format。您的代码未正确转义用户名和密码。
  • @dtb 这就是答案,如果您想将其发布为答案,我会接受。

标签: c# windows-8 microsoft-metro .net-4.5 dotnet-httpclient


【解决方案1】:

使用FormUrlEncodedContent 代替StringContentstring.Format。您的代码未正确转义用户名和密码。

HttpContent content = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("username", username),
    new KeyValuePair<string, string>("password", password),
    new KeyValuePair<string, string>("login", "Login"),
    new KeyValuePair<string, string>("keeplogged", "1")
});

【讨论】:

  • 如何将此 cookie 传递给 webview?以便我可以使用该 cookie 显示网页?
  • 这也将信息作为帖子而不是作为标题或cookie发送。如何将其作为标头/cookie 发送?
  • @MilanAggarwal:对ask at StackOverflow.com来说听起来是个好问题
  • 已经做了但没有回复here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多