2016-07-19 121 views
0

机器人:发送JSON数组节点服务器

try { 
       JSONObject obj = new JSONObject(); 
       obj.put("id", editid.getText().toString()); 
       obj.put("pw", editpassword.getText().toString()); 
       final String jsonstring = obj.toString(); 
       //final String jsonstring = "{\"id=\":\"abce\",\"pw\":\"13447\"}"; 
       Log.i("tag",jsonstring); 
       Thread background = new Thread(new Runnable() { 
        @Override 
        public void run() { 
         try { 
          Log.i("tag", "Thread"); 
          URL url = new URL("http://49.172.86.247:80/login/controller_on"); 
          HttpURLConnection hey = (HttpURLConnection) url.openConnection(); 
          hey.setRequestMethod("POST"); 
          hey.setDoInput(true); 
          hey.setDoOutput(true); 
          hey.setRequestProperty("Content-Type", "application/json"); 
          hey.setConnectTimeout(10000); 
          hey.setUseCaches(false); 

          DataOutputStream wr = new DataOutputStream(hey.getOutputStream()); 

          InputStream inputStream = hey.getInputStream(); 
          wr.writeBytes(jsonstring.toString()); 
          wr.flush(); 
          wr.close(); 

         } catch (Exception e) { 
          Log.e("tag","error"); 
         } 

服务器:

app.post('/login/:termType', function(req, res){ 
    console.log(req.body); 
}); 

我只能看到{}在节点命令提示。但通过表单标签将数据从html发送到服务器是可行的。有什么问题?

+0

使用body-parser中间件来解析json的express。 –

+0

我已经包含它,所以我可以接收来自html的数据,如 {id:'test',password:'test'}。 但我无法从android接收数据。 –

回答

0

您必须从节点服务器返回数据才能在Android中检索。

return res.status(201).json({ 
    success: true, 
    data: req.body, 
    message:'The response' 
})