Search code examples
c#jsonpostdotnet-httpclienthttpcontent

Calling REST from Windows Phone 8.1 using PostAsync, HttpClient & Json


My question is very similar to Calling MVC4 WebAPI methods from C# Metro UI Client using PostAsync, HttpClient & Json which was not sufficient for me to resolve my problem.

Here is my code in a Windows Phone 8.1 project :

using (var httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(baseAddress);
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "YW5vbnltb3VzOmFub255bW91cw==");

                var message = "{ \"userName\" : \"WebAppUser\", \"password\" : \"M@mie!duCanta1l\" }";
                var json_object = JsonConvert.SerializeObject(message);


                HttpContent content = new StringContent(json_object.ToString(), Encoding.UTF8);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");


                HttpResponseMessage response = httpClient.PostAsync(baseAddress + "/s/VpCredentials/1.0/IAuthentication/REST_JSON/Validate", content).Result;
                string statusCode = response.StatusCode.ToString();

                response.EnsureSuccessStatusCode();
                Task<string> responseBody = response.Content.ReadAsStringAsync();
            }

responseBody would always return a short piece of html with https://m.vente-privee.com/f/fail_int.png in it, indicating the call failed. The same call built in Postman in Chrome returns the following successful string :

{
    "ValidateResult": {
        "Expiration": "/Date(1404214568532+0200)/",
        "Token": "P36Hm9K9zI1gm75hfOqI6hudfdGw8y7Zu1fVgbaSHp7ayvfLUn4YtNxU/8siJ7Wa",
        "UserName": "WebAppUser"
    },
    "result": 1,
    "analytics": true
}

Postman successful call screenshot

Do you have any idea what I'm doing wrong in my C# code ? Thanks.


Solution

  • There are two problems here.

    Problem 1 - Use of HttpClient BaseAddress

    Related: Why is HttpClient BaseAddress not working?

    1. Make sure baseAddress ends with a forward slash (/).
    2. In this call, get rid of the leading forward slash (/) and don't prepend the baseAddress, which will be prepended automatically:

      (problem)

      httpClient.PostAsync(baseAddress + "/s/VpCredentials/1.0/IAuthentication/REST_JSON/Validate", content).Result;
      

      (corrected)

      httpClient.PostAsync("s/VpCredentials/1.0/IAuthentication/REST_JSON/Validate", content).Result;
      

    Problem 2 - Creation of Request Body JSON

    Don't do this:

    var message = "{ \"userName\" : \"WebAppUser\", \"password\" : \"M@mie!duCanta1l\" }";
    var json_object = JsonConvert.SerializeObject(message);
    

    That is creating a JSON-serialized string that contains JSON - a form of double-encoding which is very likely not what you want. You generally shouldn't ever be creating JSON-data string literals in your code.

    Do this:

    var message = new
    {
        userName = "WebAppUser",
        password = "M@mie!duCanta1l"
    };
    var json_object = JsonConvert.SerializeObject(message);