1

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?

bas
  • 13,550
  • 20
  • 69
  • 146
  • The former seems about right: you have to pass those values as part of the body, not the URL as you do in the second option. Can you clarify exactly what isn't working? Are you even sure that that's how it is supposed to work? Nobody sends login and password as part of the URL. – Jeroen Vannevel Aug 16 '14 at 10:52
  • Different things. One form expects parameters on the URL. The other expects data in the post content. – Stephen Chung Aug 16 '14 at 10:54
  • Try to implement this solution: http://stackoverflow.com/questions/15176538/net-httpclient-how-to-post-string-value. Maybe it solves your question – gyss Aug 16 '14 at 10:55
  • @JeroenVannevel, this is the API: http://confluence.jetbrains.com/display/YTD4/Log+in+to+YouTrack – bas Aug 16 '14 at 10:56
  • Are you sure this should be a POST if there's no body? – DavidG Aug 16 '14 at 11:10
  • It seems the REST API that you call is expecting the credential parameters in the query string. It will not try to grab them from the http content. – Yuan Shing Kong Aug 16 '14 at 11:10

1 Answers1

1

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());
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170