Domanda

Sto cercando di accedere a un sito Web usando .NET 4.5 httpclient e ricevere un cookie.Mi rompo prima di lasciare la prova e controllare il cookecontainer e non contiene cookie.La risposta invia però un 200 status di 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);
    }
.

Non ho idea perché questo non funziona.Funziona bene quando provo .NET 4 Style.

È stato utile?

Soluzione

Usa formurlencodedcontent invece di stringContent con string.format .Il tuo codice non sfugge correttamente al nome utente e alla password.

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top