【问题标题】:Sending a POST request with JSON from Android to a node.js server从 Android 向 node.js 服务器发送带有 JSON 的 POST 请求
【发布时间】:2014-03-17 18:23:09
【问题描述】:

所以我试图通过来自 Android 应用的 POST 请求将一些 JSON 发送到我的node.js 服务器。服务器托管在 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

如果有人对我收到此错误的原因有任何想法,我们将不胜感激。我花了一天的大部分时间来调试它,但我一无所获。

谢谢。

【问题讨论】:

  • 使 AsyncTask 成为子类
  • @MACMAN 我做到了。 private class postTask extends AsyncTask&lt;JSONObject, Void, String&gt; {...}

标签: android json node.js post


【解决方案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();

【讨论】:

    【解决方案2】:

    代替这个:urlConn.setRequestProperty("Content-Type","application/json"),试试这个urlConn.setRequestProperty("Content-Type","text/plain")

    这个帖子解决了这个问题,尽管是针对 Ajax 而不是 Android。

    Invalid JSON GET Request Express.js

    【讨论】:

    • 因此,当我将其切换为“text/plain”时,我没有收到 400 错误代码,但我无法在后端解析 JSON。从日志看,身体似乎是空的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 2012-04-03
    相关资源
    最近更新 更多