将JSON的POST请求从Android发送到node.js服务器 [英] Sending a POST request with JSON from Android to a node.js server

查看:83
本文介绍了将JSON的POST请求从Android发送到node.js服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图通过来自Android应用的POST请求将一些 JSON 发送到我的node.js服务器.该服务器托管在Heroku上.我非常确定服务器可以正常工作,因为当我发出curl请求时,一切都可以正常工作.我认为错误与我在前端和后端格式化 JSON 正文的方式有所不同.

So I am trying to send some JSON to a my node.js server through a POST request from an Android app. The server is hosted on Heroku. I am pretty sure that the server is working properly because when I issue a curl request, everything works properly. I think the error is something with how I am formatting the JSON body in the front-end and the back-end expecting something different.

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

This is my Android code that sends the request. This is all in a 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的调用:

Here's the call to the AsyncTask:

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

这是我的node.js后端:

And here's my node.js backend:

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的日志如下:

The result returning to my Android app is an 400 Error Code - Bad Request. And looking at Heroku's logs when I initiate the POST request is the following:

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

如果有人对我为什么收到此错误有任何想法,将不胜感激.我花了整整一天的时间来调试它,但是却一无所获.

If anyone has any ideas at to why I am getting this error, it'd be much appreciated. I've spent most of the day trying to debug this and I am getting nowhere.

谢谢.

推荐答案

cURL和HttpURLConnection -发布JSON数据

该链接上的答案对我有用.基本上,采用JSON对象并获得字节表示形式是可行的.

That answer on that link did the trick for me. Basically, taking the JSON object and getting the byte representation worked.

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

这篇关于将JSON的POST请求从Android发送到node.js服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆