Following with this BaasBox series, I previously posted BaasBox and C# from WP8 to know how to perform a log in from a WP8 App to a BaasBox server. I have accomplished that.
Now, I am facing a problem when trying to create a new record (In BaasBox it's called Document. See here) into an specific collection.
This is the code I'm using:
string sFirstName = this.txtFirstName.Text;
string sLastName = this.txtLasttName.Text;
string sAge = this.txtAge.Text;
string sGender = ((bool)this.rbtnMale.IsChecked) ? "Male" : "Female";
try
{
using(var client = new HttpClient())
{
//Step 1: Set up the HttpClient settings
client.BaseAddress = new Uri("http://MyServerDirecction:9000/document/MyCollectionName");
//client.DefaultRequestHeaders.Accept.Clear();
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Step 2: Create the request to send
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "http://MyServerDirecction:9000/document/MyCollectionName");
//Add custom header
requestMessage.Headers.Add("X-BB-SESSION", tokenId);
//Step 3: Create the content body to send
string sContent = string.Format("fname={0}&lname={1}&age={2}&gender={3}", sFirstName, sLastName, sAge, sGender);
HttpContent body = new StringContent(sContent);
body.Headers.ContentType = new MediaTypeHeaderValue("application/json");
requestMessage.Content = body;
//Step 4: Get the response of the request we sent
HttpResponseMessage response = await client.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead);
if (response.IsSuccessStatusCode)
{
//Code here for success response
}
else
MessageBox.Show(response.ReasonPhrase + ". " + response.RequestMessage);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
When testing the code above I got the following exceptionÑ
{Method: POST, RequestUri: 'http://MyServerDirecction:9000/document/MyCollectionName', Version: 1.1, Content: System.Net.Http.StringContent, Headers:
{
X-BB-SESSION: e713d1ba-fcaf-4249-9460-169d1f124cbf
Content-Type: application/json
Content-Length: 50
}}
Does anyone know how could I send an json data using HttpClient to a BaasBox Server? Or what is wrong with the code above?
Thanks in advance!
You have to send the body in the JSON format. According to the BaasBox documentation, the body payload must be a valid JSON (http://www.baasbox.com/documentation/?shell#create-a-document)
Try to format the sContent string as:
Or you can use JSON.NET (http://james.newtonking.com/json) or any other similar library to manipulate JSON stuff in a simple way.