首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在BaasBox中使用HttpClient创建文档?

在BaasBox中使用HttpClient创建文档?
EN

Stack Overflow用户
提问于 2014-09-04 04:02:53
回答 1查看 255关注 0票数 0

在这个BaasBox系列之后,我之前发布了BaasBox和C#来自WP8,以了解如何从WP8应用程序登录到BaasBox服务器。我已经做到了。

现在,在尝试创建一个新记录(在BaasBox中称为Document )时,我遇到了一个问题。请参阅这里)到特定集合中。

这是我使用的代码:

代码语言:javascript
复制
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);
}

在测试上面的代码时,我得到了以下异常

代码语言:javascript
复制
{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数据吗?或者上面的代码有什么问题?

提前感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-09-04 15:02:38

您必须以JSON格式发送身体。根据BaasBox文档,主体有效负载必须是有效的JSON (http://www.baasbox.com/documentation/?shell#create-a-document)

尝试将sContent字符串格式化为:

代码语言:javascript
复制
//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。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25657106

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档