如何将 Android 连接到 Node.js?

How to connect Android to Node.js?

我正在尝试将 Android 连接到 Node.js,我在端口 3000 中有一个服务器 运行 连接到我的本地主机,当我尝试从 POST 获取过去的数据时使用邮递员的方法,它工作得很好,但是当我用 Android whit class HttpUrlConnection 做同样的事情时,这就是结果。

Result in the server

这是来自 Node.js

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

这是来自 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();

您应该在连接到服务器之前写入数据:

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");

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

con.connect();

Android中的请求是完美的,但在 Node 中我没有使用中间件来转换正文,我使用了正文解析模块并且它有效。