1

I am having trouble with sending JSON data from my Android application written in C# using Xamarin Android (MvvmCross).

The function in Android application could run with no exception; however, my web service (written in Node JS using Express) seems not detecting the post request on its endpoint. Note that the other endpoints which use get (to send the data from web service to Android app) are working perfectly.

Below is my function to post my data to my web service

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

When running the function above, it is always succeed (return 1; always executes). I have also tried checking the JSON serialization and it is working perfectly fine.

Below also attached the endpoint code used to serve the data.

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

I tried to trace whether it reached the endpoint or not using console.log. However, it never executes.

Could you help me to spot where I went wrong? Thanks in advance.

Darren Christopher
  • 3,893
  • 4
  • 20
  • 37

1 Answers1

1

There's nothing in your .NET code that actually sends the WebRequest. You create the request, write some JSON to it's stream, and flush it. Here's a simple way to make the network call (untested):

 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;
     }
 }
Luke Pothier
  • 1,030
  • 1
  • 7
  • 19
  • Hi Luke, thank you for the help and explanation! Based on http://stackoverflow.com/a/10027534/5023889 answer, at first I thought `.Flush` is already sending the `WebRequest`. – Darren Christopher Feb 21 '17 at 08:06