【问题标题】:Why my android app isn't responding after POST method?为什么我的 android 应用在 POST 方法后没有响应?
【发布时间】:2020-03-25 20:36:14
【问题描述】:

我有问题。我正在尝试对我的 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();
        }
    }

在这里你可以找到我用来测试 JSON 解析成功的 Node.js 方法:

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

【问题讨论】:

  • 我想你是在后台线程中运行的吧?我不知道是否可以在主线程中运行网络请求,但我已经有几年没有使用 Android SDK 编写任何代码了
  • 您的 node.js 路由没有发送任何响应,因此客户端代码仍然坐在那里等待响应。至少在 node.js 路由中添加res.send("ok")res.json({status: "ok"})

标签: android node.js json post httpurlconnection


【解决方案1】:

没有看到整个代码很难知道,但你永远不会在 Node 中结束请求,所以请使用:req.send/json,否则 Android 应用程序将等待直到请求完成,这不会发生,它会超时。

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

【讨论】:

  • 当您发现错误时,您可能还想在 Android 应用中输出或记录错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-30
  • 1970-01-01
  • 1970-01-01
  • 2022-12-19
  • 1970-01-01
  • 1970-01-01
  • 2015-01-17
相关资源
最近更新 更多