volley POST json对象并从RESTful API接收json对象

时间:2016-08-19 08:18:35

标签: android json rest http-headers android-volley

我希望发送一个带有json数据的POST请求作为REST API的主体接收JSON响应。我正在使用JsonObjectRequest,我知道在JsonObjectRequest构造函数中设置jsonObject会将请求作为POST发送,否则将作为GET发送。我尝试在邮递员上执行请求,它工作正常,但在Android上,它给我错误405(方法不允许)。 REST API还要求我将Content-Type: application/json作为标头发送。这是我的代码:

JsonObjectRequest req = new JsonObjectRequest(LOGIN_ENDPOINT , payload,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {                           
                    pDialog.dismiss();
                    new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.SUCCESS_TYPE)
                            .setTitleText("Response")
                            .setContentText(response.toString())
                            .setConfirmText("Ok")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismiss();

                                }

                            })
                            .show();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {                
        pDialog.dismiss();
        new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.ERROR_TYPE)
                .setTitleText("Error")
                .setContentText(VolleyErrors.getVolleyErrorMessages(error, LoginActivity.this))                        
                .setConfirmText("Ok")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();

                    }

                })
                .show();
    }
}){
    @Override
    public byte[] getBody() {
        return payload.toString().getBytes();

    }

    @Override
    public String getBodyContentType() {
        return "application/json; charset=utf-8";
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String,String> params = new HashMap<String, String>();
        params.put("Content-Type","application/json; charset=utf-8");
        return params;
    }
};


RequestQueue requestQueue = Volley.newRequestQueue(LoginActivity.this);

requestQueue.add(req);

2 个答案:

答案 0 :(得分:0)

试试以下......

 Map<String, String> params = new HashMap<String, String>();   

     //Pass Payload as JSON object like this

       params.put("user_id", user_id);
       params.put("user_password", password);

 JSONObject payload= new JSONObject(params);


 JsonObjectRequest req = new JsonObjectRequest(Method.POST,LOGIN_ENDPOINT,payload,new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            try {                           
                pDialog.dismiss();
                new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.SUCCESS_TYPE)
                        .setTitleText("Response")
                        .setContentText(response.toString())
                        .setConfirmText("Ok")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismiss();
                            }
                        })
                        .show();

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {                

          pDialog.dismiss();
          new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.ERROR_TYPE)
            .setTitleText("Error")
            .setContentText(VolleyErrors.getVolleyErrorMessages(error, LoginActivity.this))                        
            .setConfirmText("Ok")
            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {

            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                      sweetAlertDialog.dismiss();
                  }
          })
            .show();
         }
       }) {

       @Override
       public Map<String, String> getHeaders() throws AuthFailureError {

         HashMap<String, String> headers = new HashMap<String, String>();
         headers.put("Content-Type", "application/json; charset=utf-8");
         return headers;
      }

   };

   RequestQueue requestQueue = Volley.newRequestQueue(LoginActivity.this);

   requestQueue.add(req);

答案 1 :(得分:0)

我发现问题出在REST API中,它返回了正确的预期响应,但是错误代码为405,而不是预期的200,因此用于将其选为错误。我与负责REST API的组织进行了交谈,他们修复了这些问题。上面的代码工作正常,非常感谢所有试图帮助的人