发送字符串请求后,我无法接收JSON对象中的服务器响应

时间:2017-12-16 12:14:41

标签: php android json android-volley

我的java代码如下,当用户填写必填字段,然后从服务器给出响应,无论用户是否存在。

             else {
                    StringRequest stringRequest = new StringRequest(Request.Method.POST,
                            SERVER_URL, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                String code = jsonObject.getString("code");
                                String message = jsonObject.getString("message");
                                builder.setTitle("Server response");
                                builder.setMessage(message);
                                displayAlert(code);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> params = new HashMap<String, String>();
                            params.put("name", Username);
                            params.put("email", Email);
                            params.put("password", Passwrd);

                            return params;
                        }

                        @Override
                        public RetryPolicy getRetryPolicy() {
                            setRetryPolicy(new DefaultRetryPolicy(
                                    5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                            return super.getRetryPolicy();
                        }
                    };
                    MySingleton.getInstance(Register.this).addToRequestQueue(stringRequest);
                }
            }
        }
    });

}

我需要的jsonObject响应是

{
    "code": "reg failed",
    "message": "user exists"
}

1 个答案:

答案 0 :(得分:0)

如果您希望得到的答案是您在问题中说明的JSONObject,那么您应该JSONRequest而不是StringRequest

请参阅此https://developer.android.com/training/volley/request.html