Android Volley JsonRequest

Jilberta picture Jilberta · Oct 8, 2013 · Viewed 7.3k times · Source

I want to POST JsonObject from device to server using Volley but I couldn't find any code example. If you can please provide me with some references or some code example.

Answer

A.S. picture A.S. · Oct 8, 2013

I do it this way

public void doRequest(RequestQueue volleyRequestQueue,
        onResponse responseListener) {

    this._responseListener = responseListener;

    StringRequest stringRequest = new StringRequest(Method.POST,
            Settings.QUESTIONURL, this, this) {

        public String getBodyContentType() {
            return "application/json; charset=" + getParamsEncoding();
        }

        public byte[] getBody() throws AuthFailureError {
            try {
                return new GsonBuilder()
                        .excludeFieldsWithoutExposeAnnotation().create()
                        .toJson(YOUROBJECT).toString()
                        .getBytes(getParamsEncoding());
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

    };

    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10000, MAXRETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    volleyRequestQueue.add(stringRequest);
}