0

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?

1
  • Why are you doing this? If this is an app, there are easier ways to call native code in the same process from Javascript. If this is a unit test and you're mocking the server, you're better off running the http server on the host machine. Running an HTTP server on an Android device is never a good idea, there's always better ways to do it. Commented Jul 25, 2022 at 4:15

1 Answer 1

0

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.