Tom Tom - 1 month ago 7
JSON Question

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?

Answer

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, 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,
        server_url, 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
            }
        }) {

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

requestQueue.add(request);
Comments