Search code examples
javaandroidajaxandroid-studionanohttpd

Using ajax to send back JSON to Android nanoHTTPd function


Hey all I am trying to POST some json data to my android app via Jquery AJAX and using NanoHTTPd as the web server.

I can seem to call the correct url doing this:

var reqData = JSON.stringify({"AppName": "test", "Enabled": "yes" });

$.ajax('http://10.0.2.16:8765/data', {
   data: reqData,
   dataType: 'json',
   contentType: "application/json",
   async: false,
   type: 'POST',
   success: function (data, textStatus, jqXHR) {
      alert(data);
   },
   error: function (jqXHR, textStatus, errorThrown) {
      alert("error:" + errorThrown + ' ' + reqData);
   }
});

Once I fire off that call above it goes to this java/nanoHTTPd code:

if (uri.equals("/data")) {
   try {
      session.parseBody(new HashMap<String, String>());

      System.out.println( session.getMethod() + " " + session.getParms() );

      String postBody = session.getQueryParameterString();
      String postParameter = session.getParms().get("AppName");

      return newFixedLengthResponse(
          NanoHTTPD.Response.Status.OK, 
          MIME_PLAINTEXT, 
          "It was good!"
      );
   } catch (IOException e) {
      e.printStackTrace();
      return newFixedLengthResponse(Response.Status.NOT_FOUND,"","ERROR");
   } catch (ResponseException e) {
      e.printStackTrace();
      return newFixedLengthResponse(Response.Status.NOT_FOUND,"","ERROR");
   }
}

But I am getting null for the postBody? The System.out.println shows I/System.out: POST {}

The error alert for the ajax error part dispays like this:

enter image description here

What would I be missing here in order to get the post data ajax is sending?


Solution

  • Well I figured it out finally. I needed to format my javascript code like this:

    var reqData = JSON.stringify({ data: { AppName: "test", Enabled: "yes" }});
    
    $.ajax({
       url        : "http://10.0.2.16:8765/data",
       data       : reqData,
       dataType   : "json",
       crossDomain: true,
       type       : "POST"
       headers    : {
           "Access-Control-Allow-Origin":"*"
       },             
       success    : function (data, textStatus, jqXHR) {
           $("#output").append("data: " + data.status);
       },
       error      : function (jqXHR, textStatus, errorThrown) {
           $("#output").append("error: " + errorThrown);
       }
    });
    

    And for the java code side using nanoHTTPd:

    if (uri.equals("/data")) {
        try {
            if (session.getMethod().equals(Method.POST)) {
                session.parseBody(new HashMap<String, String>());
                JSONObject mainObject = new JSONObject(session.getQueryParameterString());
                JSONObject uniObject = mainObject.getJSONObject("data");
                String appname = uniObject.getString("AppName");
                String isEnabled = uniObject.getString("Enabled");
    
                Response R = newFixedLengthResponse(NanoHTTPD.Response.Status.OK, MIME_PLAINTEXT, "{\"status\":\"It was good!\"}");
    
                R.addHeader("Access-Control-Allow-Origin", "*");
                R.addHeader("Access-Control-Allow-Methods", "POST, GET");
                R.addHeader("Access-Control-Max-Age", "86400");
    
                return R;
            }
        } catch (IOException e) {
                e.printStackTrace();
                return newFixedLengthResponse(Response.Status.NOT_FOUND,"","ERROR");
        } catch (ResponseException e) {
                e.printStackTrace();
                return newFixedLengthResponse(Response.Status.NOT_FOUND,"","ERROR");
        } catch (JSONException e) {
                e.printStackTrace();
        }
    }
    
    return  null;