使用HttpClient在BaasBox中创建文档

本文关键字:创建 文档 BaasBox HttpClient 使用 | 更新日期: 2023-09-27 18:20:31

在这个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服务器吗?或者上面的代码有什么问题?

提前感谢!

使用HttpClient在BaasBox中创建文档

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