2016-07-19 127 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' 
})