Volley json post request android

Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. Volley is available onĀ GitHub.

Find your build.gradle (app) add this under dependencies

implementation 'com.android.volley:volley:1.2.0'

Create a singleton class to manage all requests

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class AppHttp {
    private static AppHttp instance;
    private RequestQueue requestQueue;
    private static Context ctx;

    private AppHttp(Context context) {
        ctx = context;
        requestQueue = getRequestQueue();
    }

    public static synchronized AppHttp getInstance(Context context) {
        if (instance == null) {
            instance = new AppHttp(context);
        }
        return instance;
    }

    public RequestQueue getRequestQueue() {
        if (requestQueue == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            requestQueue = Volley.newRequestQueue(ctx.getApplicationContext());
        }
        return requestQueue;
    }

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

Create your POST request

AppHttp requestQueue = AppHttp.getInstance(this);
JSONObject postData = new JSONObject();
    try {
        postData.put("email", email);
        postData.put("password", password);

    } catch (JSONException e) {
        e.printStackTrace();
    }

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, "http://api.com/login", postData, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            Log.e("login response: ", response.toString());
            try {
                // Retrieve user information and take user to next activity
               // after successful login
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("login error: ", error.toString());
                error.printStackTrace();

                // show user login error with a Toast
            }
        }
    ) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("Accept", "application/json;charset=utf-8");
            params.put("Content-Type", "application/json;charset=utf-8");

            return params;
        }
    };

    requestQueue.addToRequestQueue(jsonObjectRequest);
}
Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Leave a comment