且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-01 16:51:51

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

Third parameter in JsonObjectRequest is for passing post parameters in jsonobject form. And for header you need to send two separate values one for content-type one for 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);
    } */

}