在这个BaasBox系列之后,我之前发布了BaasBox和C#来自WP8,以了解如何从WP8应用程序登录到BaasBox服务器。我已经做到了。
现在,在尝试创建一个新记录(在BaasBox中称为Document )时,我遇到了一个问题。请参阅这里)到特定集合中。
这是我使用的代码:
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);
}在测试上面的代码时,我得到了以下异常
{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
}}有人知道如何使用HttpClient向BaasBox服务器发送json数据吗?或者上面的代码有什么问题?
提前感谢!
发布于 2014-09-04 15:02:38
您必须以JSON格式发送身体。根据BaasBox文档,主体有效负载必须是有效的JSON (http://www.baasbox.com/documentation/?shell#create-a-document)
尝试将sContent字符串格式化为:
//Step 3: Create the content body to send
string sContent = string.Format("{\"fname\":\"{0}\",\"lname\":\"{1}\",\"age\":\"{2}\",\"gender\":\"{3}\"}", sFirstName, sLastName, sAge, sGender);或者可以使用JSON.NET (http://james.newtonking.com/json)或任何类似的库以简单的方式操作JSON。
https://stackoverflow.com/questions/25657106
复制相似问题