bas
bas

Reputation: 14912

How to pass variable into POST request using HttpClient

I am figuring out the new HttpClient.

I try to POST a http uri like this:

http://server/API/user/login?login=name&password=password

I thought this would be the way to go:

using (var client = new HttpClient())
{
    var values = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("login", "user"),
        new KeyValuePair<string, string>("password ", "password")
    };

    var content = new FormUrlEncodedContent(values);

    var response = await client.PostAsync("http://server/REST/user/login", content);
}

The only way I can get it to work is:

using (var client = new HttpClient())
{
    var response = await client.PostAsync("http://server/REST/user/login?login=user&password=password",null);
}

Is the last way the correct way or am I doing something wrong in the first approach?

Upvotes: 1

Views: 3141

Answers (1)

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

The sample shows that it is being passed along in the Cookie header, not the body. If I interpret the API correctly you have to indeed pass username and password in the URL and give the Cookie header the url-encoded data.

Essentially: use your second approach and for all subsequent calls, add this:

client.DefaultRequestHeaders.Add("Cookie", await content.ReadAsStringAsync());

Upvotes: 1

Related Questions