iamhssingh iamhssingh - 4 months ago 21
Android Question

Is it possible to send JSON Object instead of HASH MAP <String, String> using Volley?

I can POST

Map <String, String>
to my server but it comes in
&
separated form.

I have used code from Send post request using Volley and receive in PHP

getParams()
just doesn't work with
JSONObject
return type. Is it possible to send
JSONObject
as
JSON
only?

I want to send data as JSON that I will get using
file_get_contents(php://input)
.
For this I have changed
Content-Type
to
application/json; charset=utf-8
.

The problem is using this way I get data in format of
x=abc&y=def
as it's
Map<String, String>
type and I want data in
JSON
format of
{"x":"abc", "y":"def"}


It's different from above question because I want to POST data in JSON ONLY and not in MAP of String

Answer

Try this :

private void jsonObjReq() {

        showProcessDialog();
        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;
    }



};

change header in your php too.