【问题标题】:how to send json object to server using volley in android如何在 android 中使用 volley 将 json 对象发送到服务器
【发布时间】:2015-04-05 08:04:53
【问题描述】:

我想使用 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: Unexpected response code 401

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

【问题讨论】:

  • JsonObjectRequest 中的第三个参数用于以 jsonobject 形式传递 post 参数。对于标头,您需要发送两个单独的值,一个用于内容类型,一个用于字符集。
  • @Pr38y : getParams() 将是 JsonObjectRequest 中的第三个参数,对吗???和 headers.put("Content-Type", "charset=utf-8");是这样吗??

标签: android json android-volley


【解决方案1】:

创建新方法并在 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);

    }

【讨论】:

    【解决方案2】:

    JsonObjectRequest 中的第三个参数用于以 jsonobject 形式传递 post 参数。对于标头,您需要发送两个单独的值,一个用于内容类型,一个用于字符集。

      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 类?
    • @John 能否请您将您的全班齐射 [java 文件] 发送到我的电子邮件地址:arsalanali13@gmail.com,我将非常感谢您
    • 我面临同样的问题,这就是为什么要提前询问您完整的 java 文件..THnks
    • @ArslanAliAwan 如果您遇到问题,我早就更新了我的代码。向我解释问题,以便我可以帮助您
    • @John 请在这里查看我的类似问题stackoverflow.com/questions/35067507/…
    猜你喜欢
    • 2014-11-06
    • 1970-01-01
    • 2018-09-24
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多