Nodejs req.body从Android Volley显示为空

时间:2017-06-07 17:18:47

标签: android android-volley

Android代码:

private void registerUser(){
        final String username = "subrata";
        final String password = "banerjee";
        final String email = "test_email";

        StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                    }
                }){
            @Override
            protected Map<String,String> getParams(){
                Map<String,String> params = new HashMap<String, String>();
                params.put(KEY_USERNAME,username);
                params.put(KEY_PASSWORD,password);
                params.put(KEY_EMAIL, email);
                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

我尝试使用 Android Volley 向我的node.js服务器(expressjs)发送http请求。它命中服务器并获得响应但是当我在node.js中打印req.body时,它显示{}(空)。我是Android的新手,无法弄清楚原因。请有人指导我。

2 个答案:

答案 0 :(得分:0)

在OnResponse GetResponse(response);中调用此方法 方法将是

private void GetResponse(String res){
    JSONObject jsonObject = null;

    try {
        jsonObject = new JSONObject(res);
        JSONArray result = jsonObject.getJSONArray("result");

        for (int i = 0; i < result.length(); i++) {
            JSONObject jo = result.getJSONObject(i);
            String temp = jo.getString("what_ever");
            String temp1 = jo.getString("what_ever_1");
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

这将为您提供从json获取的String格式的响应。

答案 1 :(得分:0)

System.setProperty("Log4jContextSelector",
        "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");