Reputation: 27
I have a problem. I'm trying to execute POST method to my Node.js server. After POST method I'm getting all the data in server but then my app isn't responding a few seconds. Is there some bugs in my code?
My POST method:
public static void setTemp(String address, String hot, String cold) throws IOException
{
URL url = new URL(address); //in the real code, there is an ip and a port
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
try {
conn.connect();
JSONObject jsonParam = new JSONObject();
jsonParam.put("hot", hot);
jsonParam.put("cold", cold);
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
os.writeBytes(jsonParam.toString());
os.flush();
os.close();
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG" , conn.getResponseMessage());
} catch (Exception e) {
}
finally {
conn.disconnect();
}
}
This is how I call the POST method:
private void setTemp(String hot, String cold)
{
try {
WebAPI.setTemp(Tools.RestURLPost, hot, cold);
}
catch(IOException e) {
e.printStackTrace();
}
}
And here you can find my Node.js method which I use to test successful parsing of JSON:
router.post('/post', function(req, res, next) {
console.log(req.body);
});
Upvotes: 0
Views: 143
Reputation: 40434
Without seeing the whole code it's hard to know but you're never ending the request in Node, so use: req.send/json
, otherwise the Android application will wait until the request is done, which won't happen and it will timeout.
router.post('/post', function(req, res, next) {
console.log(req.body);
res.json({ success: true });
});
Upvotes: 1