Mahith Amancherla
Mahith Amancherla

Reputation: 73

Sending a POST request with JSON from Android to a node.js server

So I am trying to send some JSON to a my node.js server through a POST request from an Android app. The server is hosted on Heroku. I am pretty sure that the server is working properly because when I issue a curl request, everything works properly. I think the error is something with how I am formatting the JSON body in the front-end and the back-end expecting something different.

This is my Android code that sends the request. This is all in a AsyncTask:

HttpURLConnection urlConn = null;
        String result = "-1";
        JSONObject json = jsonParam[0];
        Log.d("postTask: JO",json.toString());
        try {
            URL url;
            DataOutputStream printout;
            String address = BASE_URL+"/users/add";
            Log.d("sendPost",address);
            url = new URL (address);
            urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setDoInput (true);
            urlConn.setDoOutput (true);
            urlConn.setUseCaches (false);
            urlConn.setRequestMethod("POST");
            urlConn.setChunkedStreamingMode(100);
            urlConn.setRequestProperty("Content-Type","application/json");   
            urlConn.connect();  
            // Send POST output.
            printout = new DataOutputStream(urlConn.getOutputStream());
            String output = URLEncoder.encode(json.toString(),"UTF-8");
            Log.d("postTaskURL",output);
            printout.writeUTF(json.toString());
            printout.flush();
            result = Integer.toString(urlConn.getResponseCode());
            printout.close();
        } catch (IOException e) {
            e.printStackTrace();
        }  finally {
            if(urlConn !=null)  
                   urlConn.disconnect(); 
        }
        return result;

Here's the call to the AsyncTask:

            postTask task = new postTask();
            JSONObject json = new JSONObject();
            json.put("username","user");
            json.put("password","life");
            task.execute(json);

And here's my node.js backend:

app.post('/users/add',function(req, res) {
console.log("MADE IT TO THIS FUNCTION");
var user = req.body.user;
var password = req.body.password;
console.log("User: " + user + "\nPassword: " + password);
var rC = model.add(user,password, function(returnCode){
    console.log("returnCode: " + returnCode.toString());
    sendJSON(res,returnCode);
});
if (rC != undefined && rC != null) {
    sendJSON(res, rC);
}
});

The result returning to my Android app is an 400 Error Code - Bad Request. And looking at Heroku's logs when I initiate the POST request is the following:

Error: invalid json
2014-02-18T06:13:25.468224+00:00 app[web.1]:     at Object.exports.error  (/app/node_modules/express/node_modules/connect/lib/utils.js:60:13)
2014-02-18T06:13:25.468224+00:00 app[web.1]:     at IncomingMessage.<anonymous> (/app/node_modules/express/node_modules/connect/lib/middleware/json.js:74:71)
2014-02-18T06:13:25.468224+00:00 app[web.1]:     at IncomingMessage.EventEmitter.emit (events.js:92:17)
2014-02-18T06:13:25.468224+00:00 app[web.1]:     at process._tickCallback (node.js:415:13)
2014-02-18T06:13:25.468224+00:00 app[web.1]:     at _stream_readable.js:920:16
2014-02-18T06:13:25.499015+00:00 heroku[router]: at=info method=POST path=/users/add host=ancient-spire-1285.herokuapp.com request_id=5d148ef8-a74b-4cd5-ae8b-67f0214ee641 fwd="76.102.205.187" dyno=web.1 connect=1ms service=310ms status=400 bytes=521

If anyone has any ideas at to why I am getting this error, it'd be much appreciated. I've spent most of the day trying to debug this and I am getting nowhere.

Thanks.

Upvotes: 1

Views: 8092

Answers (2)

Mahith Amancherla
Mahith Amancherla

Reputation: 73

cURL and HttpURLConnection - Post JSON Data

That answer on that link did the trick for me. Basically, taking the JSON object and getting the byte representation worked.

byte[] outputBytes = "{'value': 7.5}".getBytes("UTF-8");
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);
os.close();

Upvotes: 1

JustSoAmazing
JustSoAmazing

Reputation: 747

Instead of this: urlConn.setRequestProperty("Content-Type","application/json"), try doing this urlConn.setRequestProperty("Content-Type","text/plain").

This thread addresses this issue, albeit for Ajax instead of Android.

Invalid JSON GET Request Express.js

Upvotes: 0

Related Questions