2014-09-04 54 views
0

繼此BaasBox系列之後,我先前發佈了BaasBox and C# from WP8 瞭解如何執行從WP8應用程序登錄到BaasBox服務器。我已經完成了。使用HttpClient在BaasBox中創建文檔?

現在,在嘗試創建新記錄(在BaasBox中稱爲Document,請參見here)時,我遇到了一個問題。

這是我使用的代碼:

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); 
} 

當測試上面的代碼,我得到了以下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 
}} 

有誰知道我怎麼能使用HttpClient的一個JSON數據發送到一個BaasBox服務器?或者上面的代碼有什麼問題?

在此先感謝!

回答

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內容。

+0

嗨Giastfader。 Thaks爲你提供幫助。但是,不確定問題是JSON格式(我使用了與實現登錄時發佈的相同的方法並且它工作正常)。我嘗試了你的建議,它會拋出一個例外,即字符串的格式不正確。我的猜測是,它似乎與sContent內容的添加位置有關。我的意思是在標題或正文中。 – MikePR 2014-09-04 23:52:18

+0

再次嗨。畢竟,似乎你的建議是確定的。做一些測試我發現我得到錯誤的其中一個問題是字符串格式不正確。我使用下面這行代碼:string sContent = JsonConvert.SerializeObject(personData);導致問題的另一件事是該字符串中的數據,我沒有正確設置。解決這兩個問題,現在我可以添加一條新記錄。 – MikePR 2014-09-05 01:03:36