Xamarin Android客户端发布JSON到Node JS Web服务

我使用Xamarin Android( MvvmCross )从使用C#编写的Android应用程序发送JSON数据时遇到了问题。

Android应用程序中的函数可以毫不例外地运行, 但是,我的Web服务(使用Express写在Node JS中)似乎没有检测到其端点上的发布请求。 请注意,使用get (从Web服务发送数据到Android应用程序)的其他terminal正在运行完美。

以下是我的数据发布到我的Web服务的function

 public async Task<int> insertSales(IEnumerable<Models.SalesTable> newsales) { /*ServerDatabaseApi.insertSalesEndpoint = "http://" + ipAddress + ":" + port + "/insertsales";*/ WebRequest request = WebRequest.CreateHttp(ServerDatabaseApi.insertSalesEndpoint); request.Method = "POST"; request.ContentType = "application/json"; try { using (var streamwriter = new StreamWriter(await request.GetRequestStreamAsync())) { string json = JsonConvert.SerializeObject(newsales, Formatting.Indented); streamwriter.Write(json); streamwriter.Flush(); } return 1; } catch (WebException we) { return 0; } } 

运行上面的函数时,总是成功( return 1;始终执行)。 我也试着检查JSON序列化,它工作得很好。

下面还附加了用于提供数据的端点代码。

 /*endpoint for inserting a new sales to sales table*/ app.post('/insertsales', function(appReq, appRes){ console.log("Insert sales; count : "+ appReq.body.length); sql.connect(conn).then(function(){ console.log("Insert sales; count : "+ appReq.body.length); for (var i = 0 ; i < appReq.body.length ; i++) { new sql.Request() .query("insert into SalesTable " + "values ('"+appReq.body[i].DocumentNo+"','"+appReq.body[i].DateCreated+"','"+appReq.body[i].Location+"',"+ appReq.body[i].TotalDiscountAmount+","+appReq.body[i].Total+",'"+appReq.body[i].SalesmanId+"','"+ appReq.body[i].CustomerId+"',"+appReq.body[i].Latitude+","+appReq.body[i].Longitude+")") .catch(function(err){ console.log(err); }); } }).catch(function(err){ console.log(err); }); }); 

我试图跟踪是否到达终点或不使用console.log 。 但是,它永远不会执行。

你能帮我找出我出错的地方吗? 提前致谢。

实际上发送WebRequest .NET代码中没有任何东西。 你创build请求,写一些JSON到它的stream,然后刷新它。 这是一个简单的方法来进行networking调用(未经testing):

  public async Task<int> InsertSales(IEnumerable<Models.SalesTable> newSales) { var ipAddress = "";// your IP address here var port = ""; // your port here var endpoint = $"http://{ipAddress}:{port}/insertsalesline"; var requestString = JsonConvert.SerializeObject(newSales); var content = new StringContent(requestString, Encoding.UTF8, "application/json"); using (var client = new HttpClient()) { var reponse = await client.PostAsync(endpoint, content); if (reponse.IsSuccessStatusCode) return 1; else return 0; } }