【问题标题】:How to connect Android to Node.js?如何将 Android 连接到 Node.js?
【发布时间】:2018-05-14 20:18:09
【问题描述】:

我正在尝试将 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'
  });
});

这是来自安卓

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

【问题讨论】:

  • 您是否尝试过使用con.setDoInput(true)
  • 可以,但是问题是服务器什么都没有收到,只收到请求不收到数据。

标签: android node.js post httpurlconnection


【解决方案1】:

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

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

【讨论】:

  • 不起作用:( ....我正在调试,当我在下一行中进行wrt.flush() wrt 仍然有数据...我认为数据没有'不发送,但请求是的,因为服务器中有一个空的req.query
  • @DavidSotelo 我已经简化了 BufferedWriter,现在就试试吧。
【解决方案2】:

Android 中的请求是完美的,但是在 Node 中我没有使用中间件来转换正文,我使用了 body-parse 模块并且它可以工作。

【讨论】:

    猜你喜欢
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    • 2018-01-07
    • 2015-09-10
    • 1970-01-01
    相关资源
    最近更新 更多