0

I'm using the following code to post a message to the server.

String credentials="email=me@here.com&pass=abc123";
using (HttpClient client = new HttpClient())
{
  HttpResponseMessage message = await client.PostAsync(
    url, new StringContent(credentials));
  result = await message.Content.ReadAsStringAsync();
}

However, the server responds with an error message saying that the email or pass isn't there.

{\"status\":\"error\",\"message\":\"Email or pass is missing\"}

Now, I can see it's lying but what can be done about it? Am I not providing the credentials as post data (the equivalent of "params" that can be seen if invoked from URL line in FF, as the image below shows?

I also noticed that when I access the RequestMessage like below, I get the URL but no credentials having been sent. What stupid thing am I missing?!

result = message.RequestMessage.ToString();

This result gives me the following string.

Method: POST, RequestUri: 'https://server.com/gettoken', Version: 1.1, Content: System.Net.Http.StringContent, Headers:\u000d\u000a{\u000d\u000a Content-Type: text/plain; charset=utf-8\u000d\u000a Content-Length: 56\u000d\u000a}

enter image description here

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
  • The default format for POST requests (e.g. from actual HTML forms) is `application/x-www-form-urlencoded`, in which keys are separated from values **with an equals sign (`=`)**. – voithos Nov 12 '14 at 23:26
  • @voithos Good eyes, mate! I corrected the text. It's equality sign - I just miswrote when editing my real credentials. Also, I added a new line about *RequestMessage*. Any ideas now? – Konrad Viltersten Nov 12 '14 at 23:32
  • 1
    You should probably try using `FormUrlEncodedContent` instead of `StringContent`. See this answer: http://stackoverflow.com/a/20005964/716118 – voithos Nov 12 '14 at 23:35
  • @voithos (a) Post this as a reply because it freaking worked! Awesome! (b) I still don't get to see the parameters in the *RequestMessage*... I'm getting the right token and stuff, though, but still... – Konrad Viltersten Nov 12 '14 at 23:46
  • It's likely due to the `ToString()` implementation of `HttpRequestMessage`. Try checking `message.Content.ToString()` – voithos Nov 13 '14 at 00:07

1 Answers1

5

You should use the FormUrlEncodedContent to pass your POST data, instead of a StringContent object.

var credentials = new FormUrlEncodedContent(new[] {
  new KeyValuePair<string, string>("email", "me@here.com"), 
  new KeyValuePair<string, string>("pass", "abc123") 
});

using (HttpClient client = new HttpClient())
{
  HttpResponseMessage message = await client.PostAsync(
    url, credentials);
  result = await message.Content.ReadAsStringAsync();
}
voithos
  • 68,482
  • 12
  • 101
  • 116