Search code examples
androidnode.jsposthttpurlconnection

How to connect Android to Node.js?


I'm trying to connect Android to Node.js, i have a server running in port 3000 to my localhost, when i try past data from POST method using postman, it works perfectly, but when i do the same with Android whit class HttpUrlConnection this is the result.

Result in the server

this is the code from Node.js

router.post('/', (req, res)=>{
  console.log(req.query);
  res.send({
    mensaje: 'I am from usuario routes'
  });
});

and this is from android

    URL obj = new URL("http://192.168.1.107:3000/");
JSONObject jsonObject = new JSONObject();
jsonObject.put("image", "imagen");
String data = jsonObject.toString();
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setDoOutput(true);
//con.setDoInput(true);
con.setRequestMethod("POST");
con.setConnectTimeout(5000);
con.setFixedLengthStreamingMode(data.getBytes().length);
con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
con.connect();

OutputStream out = new BufferedOutputStream(con.getOutputStream());
BufferedWriter wrt = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
wrt.append(data);
wrt.flush();

wrt.close();
out.close();
con.disconnect();

Solution

  • The request in Android is perfect, but in Node i was not using a middleware to convert the body, i used body-parse module and it works.