为什么我的android应用在POST方法后没有响应?

时间:2019-11-30 17:15:10

标签: android node.js json post httpurlconnection

我有问题。我正在尝试对我的Node.js服务器执行POST方法。使用POST方法后,我将获取服务器中的所有数据,但是我的应用程序几秒钟没有响应。我的代码中有一些错误吗?

我的POST方法:

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();
        }
    }

这就是我所谓的POST方法:

    private void setTemp(String hot, String cold)
    {
        try {
            WebAPI.setTemp(Tools.RestURLPost, hot, cold);
        }
        catch(IOException e) {
            e.printStackTrace();
        }
    }

在这里您可以找到我的Node.js方法,该方法用于测试JSON的成功解析:

router.post('/post', function(req, res, next) {
  console.log(req.body);
});

1 个答案:

答案 0 :(得分:1)

很难看到完整的代码,但是您永远不会在Node中结束请求,因此请使用:req.send/json,否则Android应用程序将等待直到请求完成为止,这不会发生,并且它将超时。

router.post('/post', function(req, res, next) {
  console.log(req.body);
  res.json({ success: true });
});