Android Volley library - Fixing the empty POST parameters

Recently, I came across the Volley library for Android.

I already had an app that used network requests, to post and get data from a Node.js webserver with Express.js.

The code I had for doing the network part, downloading JSON data and images, with memory and disk cache of images, was working fine, but I thought I’d make use of volley instead. As it had better support for certain things, one of them; grouping and cancelling requests by using tags.

After some time, developing the app, and doing JSON requests against a local node.js server, over HTTP, I began testing my app against a identical, but remote node.js server, over HTTPS.

I was quite surprised to find that the requests did not work the same way.

Empty POST parameters

The JSON requests were all failing, because on the serverside, all POST parameters were empty!  My node.js server with Express, was using the express.bodyparser(), which previously had worked just fine locally.
What was also weird, was that the headers were working just fine.

After lots of searching, and asking for help in the Volley users group, I came across a tip, to set the charset on the content type header. Because without it, the bodyparser fails to parse that parameters correctly.

So, the correct content-type headers should be:

application/json; charset=utf-8

As I did not previously set the charset=utf-8 part, my requests were failing.

The working code for doing a JSON POST request with Volley

(Excluding the setup of Volley itself)

The correct content-type header is set at line 25.

Map<String, String> jsonParams = new HashMap<String, String>();  
jsonParams.put("param1", youParameter);

JsonObjectRequest myRequest = new JsonObjectRequest(  
        new JSONObject(jsonParams),

        new Response.Listener<JSONObject>() {
            public void onResponse(JSONObject response) {
        new Response.ErrorListener() {
            public void onErrorResponse(VolleyError error) {
        }) {

    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json; charset=utf-8");
        headers.put("User-agent", "My useragent");
        return headers;
MyApplication.getInstance().addToRequestQueue(myRequest, "tag");  
comments powered by Disqus