使用JSON从Android发送POST请求到node.js服务器

时间:2014-02-18 06:52:19

标签: android json node.js post

因此,我尝试通过Android应用的POST请求向我的node.js服务器发送一些 JSON 。服务器托管在Heroku上。我很确定服务器工作正常,因为当我发出curl请求时,一切正常。我认为错误与我如何格式化前端的 JSON 主体以及期望不同的后端有关。

这是我发送请求的Android代码。这一切都在 AsyncTask

HttpURLConnection urlConn = null;
        String result = "-1";
        JSONObject json = jsonParam[0];
        Log.d("postTask: JO",json.toString());
        try {
            URL url;
            DataOutputStream printout;
            String address = BASE_URL+"/users/add";
            Log.d("sendPost",address);
            url = new URL (address);
            urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setDoInput (true);
            urlConn.setDoOutput (true);
            urlConn.setUseCaches (false);
            urlConn.setRequestMethod("POST");
            urlConn.setChunkedStreamingMode(100);
            urlConn.setRequestProperty("Content-Type","application/json");   
            urlConn.connect();  
            // Send POST output.
            printout = new DataOutputStream(urlConn.getOutputStream());
            String output = URLEncoder.encode(json.toString(),"UTF-8");
            Log.d("postTaskURL",output);
            printout.writeUTF(json.toString());
            printout.flush();
            result = Integer.toString(urlConn.getResponseCode());
            printout.close();
        } catch (IOException e) {
            e.printStackTrace();
        }  finally {
            if(urlConn !=null)  
                   urlConn.disconnect(); 
        }
        return result;

这是对AsyncTask的调用:

            postTask task = new postTask();
            JSONObject json = new JSONObject();
            json.put("username","user");
            json.put("password","life");
            task.execute(json);

这是我的node.js后端:

app.post('/users/add',function(req, res) {
console.log("MADE IT TO THIS FUNCTION");
var user = req.body.user;
var password = req.body.password;
console.log("User: " + user + "\nPassword: " + password);
var rC = model.add(user,password, function(returnCode){
    console.log("returnCode: " + returnCode.toString());
    sendJSON(res,returnCode);
});
if (rC != undefined && rC != null) {
    sendJSON(res, rC);
}
});

返回我的Android应用程序的结果是400错误代码 - 错误请求。当我发起POST请求时查看Heroku的日志如下:

Error: invalid json
2014-02-18T06:13:25.468224+00:00 app[web.1]:     at Object.exports.error  (/app/node_modules/express/node_modules/connect/lib/utils.js:60:13)
2014-02-18T06:13:25.468224+00:00 app[web.1]:     at IncomingMessage.<anonymous> (/app/node_modules/express/node_modules/connect/lib/middleware/json.js:74:71)
2014-02-18T06:13:25.468224+00:00 app[web.1]:     at IncomingMessage.EventEmitter.emit (events.js:92:17)
2014-02-18T06:13:25.468224+00:00 app[web.1]:     at process._tickCallback (node.js:415:13)
2014-02-18T06:13:25.468224+00:00 app[web.1]:     at _stream_readable.js:920:16
2014-02-18T06:13:25.499015+00:00 heroku[router]: at=info method=POST path=/users/add host=ancient-spire-1285.herokuapp.com request_id=5d148ef8-a74b-4cd5-ae8b-67f0214ee641 fwd="76.102.205.187" dyno=web.1 connect=1ms service=310ms status=400 bytes=521

如果有人对我收到此错误的原因有任何想法,我们将不胜感激。我花了大部分时间试图调试这个,但我无处可去。

感谢。

2 个答案:

答案 0 :(得分:1)

cURL and HttpURLConnection - Post JSON Data

那个链接上的答案对我有用。基本上,获取JSON对象并获取字节表示。

byte[] outputBytes = "{'value': 7.5}".getBytes("UTF-8");
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);
os.close();

答案 1 :(得分:0)

而不是:urlConn.setRequestProperty("Content-Type","application/json"),请尝试执行此操作urlConn.setRequestProperty("Content-Type","text/plain")

该线程解决了这个问题,尽管是针对Ajax而不是Android。

Invalid JSON GET Request Express.js