posting data to server in json format using volley

。_饼干妹妹 提交于 2019-12-01 19:48:18

Have a singleton which handles the request queue.

public class VolleySingleton {

    // Singleton object...
    private static VolleySingleton instance;

    final private RequestQueue requestQueue;
    private static ImageLoader imageLoader;

    //Constructor...
    private VolleySingleton(Context context) {

        requestQueue = Volley.newRequestQueue(context);

        imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
            private final LruCache<String, Bitmap> cache = new LruCache<>(100000000);


            @Override
            public Bitmap getBitmap(String url) {
                return cache.get(url);
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                cache.put(url, bitmap);
            }
        });
    }

    // Singleton method...
    public static VolleySingleton getInstance(Context context) {
        if (instance == null) {
            instance = new VolleySingleton(context);
        }
        return instance;
    }

    public RequestQueue getRequestQueue(Context context) {
        if (requestQueue != null) {
        return requestQueue;
        } else {
            getInstance(context);
            return requestQueue;
        }
    }

    private  RequestQueue getRequestQueue() {
        return requestQueue;
    }

    public static ImageLoader getImageLoader(Context context) {
        if (imageLoader != null) {
            return imageLoader;
        } else {
            getInstance(context);
            return imageLoader;
        }
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag("App");
        getRequestQueue().add(req);
    }

}

Then using the below method you can send the request.

public void postVolley(final Context context, String url, JSONObject jsonObject) {

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject responseJson) {
                Log.e("success", "" + responseJson.toString());
            }


        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("error", "" + error);

            }
        }) {

            /**
             * Setting the content type
             */

            @Override
            public String getBodyContentType() {
                return "application/json;charset=UTF-8";
            }
        };

        VolleySingleton.getInstance(context).addToRequestQueue(jsonObjReq);

    }

This works fine for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!