0

在这个 BaasBox 系列之后,我之前发布了来自 WP8 的BaasBox 和 C#, 以了解如何从 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 将 json 数据发送到 BaasBox 服务器?或者上面的代码有什么问题?

提前致谢!

4

1 回答 1

1

您必须以 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 内容。

于 2014-09-04T15:02:38.747 回答