4

我正在尝试使用 .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 风格时,它工作正常。

4

1 回答 1

7

使用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")
});
于 2012-07-26T00:49:08.953 回答