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

问题描述 投票:0回答:1

我有问题。我正在尝试对我的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);
});
android node.js json post httpurlconnection
1个回答
0
投票

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

router.post('/post', function(req, res, next) {
  console.log(req.body);
  res.json({ success: true });
});
© www.soinside.com 2019 - 2024. All rights reserved.