如何在Android中使用Volley将JSON对象发送到服务器

12
我想使用POST方法将JSONObject发送到服务器。我已经使用了volley库来传递字符串参数,它可以正常工作,但是如果我尝试使用json对象,则会显示调用json对象的错误。这是我的代码。
    private void makeJsonObjReq() {
    showProgressDialog();
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
            Const.URL_LOGIN, null,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, response.toString());
                    msgResponse.setText(response.toString());
                    hideProgressDialog();
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    hideProgressDialog();
                }
            }) {

        /**
         * Passing some request headers
         * */
        @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;
        }

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("un", "xyz@gmail.com");
            params.put("p", "somepasswordhere");
            return params;
        }

    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq,tag_json_obj);

    // Cancelling request
    // ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_obj);       
}

我的服务器错误信息为:[10031] BasicNetwork.performRequest: 返回码 401,响应不符合预期

如何解决这个问题。我想在头部添加application/json;charset=utf-8 ,请检查我的代码是否正确。请给我一些建议来克服这个问题。


JsonObjectRequest中的第三个参数用于以JsonObject形式传递POST参数。而对于头部,您需要发送两个单独的值,一个用于Content-Type,另一个用于Charset。 - Pr38y
@Pr38y:getParams()会是JsonObjectRequest中的第三个参数,对吗?而headers.put("Content-Type", "charset=utf-8");是正确的吗? - John
2个回答

29

JsonObjectRequest的第三个参数是用于以JsonObject形式传递POST参数。对于标题(header),您需要发送两个单独的值,一个是content-type,另一个是charset。

  RequestQueue queue = Volley.newRequestQueue(this);

  private void makeJsonObjReq() {
    showProgressDialog();


            Map<String, String> postParam= new HashMap<String, String>();
            postParam.put("un", "xyz@gmail.com");
            postParam.put("p", "somepasswordhere");


    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
            Const.URL_LOGIN, new JSONObject(postParam),
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, response.toString());
                    msgResponse.setText(response.toString());
                    hideProgressDialog();
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    hideProgressDialog();
                }
            }) {

        /**
         * Passing some request headers
         * */
        @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;
        }



    };

    jsonObjReq.setTag(TAG);
    // Adding request to request queue
    queue.add(jsonObjReq);

    // Cancelling request
    /* if (queue!= null) {
    queue.cancelAll(TAG);
    } */

}

JsonObject类是什么? - Harsh Vardhan
@John,你能否把这个Volley [Java文件]的整个类发送到我的电子邮件地址arsalanali13@gmail.com?我将非常感激。 - robinHood013
我遇到了同样的问题,这就是我为什么要问你完整的Java文件的原因。提前感谢您。 - robinHood013
@ArslanAliAwan 你在哪里遇到问题了,我很久以前就更新了我的代码。请解释一下问题,这样我就可以帮助你。 - John
@John,请在这里检查我的类似问题http://stackoverflow.com/questions/35067507/how-to-send-sqlite-data-from-android-to-mysql-server?noredirect=1#comment57859091_35067507 - Steve Kamau
如果您使用ASP Web API作为API服务,请确保您的方法参数包含在对象中。 - Setmax

0
创建新的方法并在OnClick方法中调用它。
public void PostOperation() {
        requestQueue = Volley.newRequestQueue(this);
        pdialog = new ProgressDialog(this);
        pdialog.setMessage("Loading");
        pdialog.show();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, "YOUR_URL",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        pdialog.dismiss();
                        Log.e("login output", response);
//MODEL CLASS
                       LoginModel loginModel = new GsonBuilder().create().fromJson(response, LoginModel.class);


                        if (loginModel.getStatus().toString().equalsIgnoreCase("true")) {


                            Intent i = new Intent(context, DashboardActivity.class);
                            startActivity(i);
                            finish();

                            Toast.makeText(context, loginModel.getStatus() + "", Toast.LENGTH_SHORT).show();
                        } else {

                            Toast.makeText(context, loginModel.getMsg() + "", Toast.LENGTH_SHORT).show();

                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        pdialog.dismiss();
                        Toast.makeText(getApplicationContext(), "Invalid Credentials", Toast.LENGTH_SHORT).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                HashMap<String, String> map = new HashMap<String, String>();

              // pass your input text

                map.put("email" editTextEmail.getText().toString()); 
                map.put("password",editTextPassword.getText().toString() );

                map.put("uid", "1"); 
                map.put("type", "login");


                Log.e("para", map + "");
                return map;
            }

        };
        requestQueue.add(stringRequest);

    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接