user6742489
user6742489

Reputation:

How to add JSON header

My code to sent JSONArray to server...

   StringRequest request= new StringRequest(Request.Method.POST, server_url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Toast.makeText(getApplicationContext(), " Successfull", Toast.LENGTH_SHORT).show();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }){
            public Map<String,String> getParams() throws AuthFailureError {
                Map<String,String> parameters = new HashMap<String, String>();
                getResults().put(parameters);
                return parameters;


            }
        };

        requestQueue.add(request);
    }

This code is used to sent JSONArray to the server. How can I set a header so the the server can identify that its a JSON file. How can I do it?

Upvotes: 3

Views: 1021

Answers (1)

earthw0rmjim
earthw0rmjim

Reputation: 19417

The simpliest way to set the Content-Type header field of your Request might be to override getBodyContentType():

@Override
public String getBodyContentType() {
    return "application/json";
}

If you would like to send JSON in the body of your POST request, you should use either JsonObjectRequest or JsonArrayRequest.

For example, if your getResults() method returns a JSONArray that you would like to send as the body of the request, you could do something like this:

JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST,
        serverUrl, getResults(),
        new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                // handle the response
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // an error occurred
            }
        });

requestQueue.add(request);

Upvotes: 3

Related Questions