[英]Creating a document in BaasBox using HttpClient?
在這個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服務器? 還是上面的代碼有什么問題?
提前致謝!
您必須以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內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.