我正在尝试使用.net 4.5 httpclient登录网站并接收cookie。在离开尝试之前,我会突破并检查cookiecontainer,它不包含饼干。响应虽然发送了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 。您的代码不正确地转义用户名和密码。

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")
});
.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top