¿如何将Android与Node.js联系起来?

时间:2017-11-30 19:36:27

标签: android node.js post httpurlconnection

我正在尝试将Android连接到Node.js,我有一个服务器在端口3000中运行到我的localhost,当我尝试使用postman的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();

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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