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

Volley offers the following benefits:

  • Automatic scheduling of network requests.

  • Multiple concurrent network connections.

  • Transparent disk and memory response caching with standard HTTP cache coherence.

  • Support for request prioritization.

  • Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel.

  • Ease of customization, for example, for retry and backoff.

  • Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.

  • Debugging and tracing tools.

1. Create a new project in Android Studio from File ⇒ New Project. Like this com.appcode.activity.

2. Now open the build.gradle located in project’s home directory and add volley dependency.


dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'

compile 'com.android.support:appcompat-v7:24.2.0'
compile 'com.android.support:design:24.2.0'
compile 'com.google.code.gson:gson:2.2.4'
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
}

3 . Create a class name MainActivity.java under your project.

package com.appcode.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.android.volley.Request;

import org.json.JSONObject;

import com.appcode.R;
import com.appcode.VolleyResponseListener;
import com.appcode.VolleyWebService;

public class MainActivity extends AppCompatActivity {

private Button buttonApiCall;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        buttonApiCall=(Button) findViewById(R.id.buttonApiCall);
        
        
        buttonApiCall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            apiCall(); //Post call method
            }
        });
    }
    
    public void apiCall()
    {
    // url = // put your base url like this "http://www.gkmit.co/front/login"
    VolleyWebService.makeJsonObjectRequest(MainActivity.this, Request.Method.POST, url, jsonObject, new VolleyResponseListener()
        {
            @Override
            public void onResponse(JSONObject response) {
               
            }

            @Override
            public void onError(String message) {
                Toast.makeText(MainActivity.this, "Some Error fetching Data !!", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

4. Create a interface name VolleyResponseListener.java under your project.

package com.appcode.webservices;

import org.json.JSONObject;

/**
 * Created by sikander on 21/01/17.
 */

public interface VolleyResponseListener {
    void onError(String message);

    void onResponse(JSONObject response);
}


5. Create a class name VolleyWebService.java under your project.

package com.appcode.webservices;

import android.app.ProgressDialog;
import android.content.Context;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import gkmit.grealthfresh.utils.AppController;
import gkmit.grealthfresh.utils.Constants;

/**
 * Created by sikander on 21/01/17.
 */

public class VolleyWebService {

    public static void makeJsonObjectRequest(Context context, int method, String url, JSONObject jsonObject ,final VolleyResponseListener listener) {
        final ProgressDialog progressDialog = ProgressDialog.show(context, null, "Loading...", false, false);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                (method, url, jsonObject, new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        listener.onResponse(response);
                        progressDialog.dismiss();
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        listener.onError(error.toString());
                        progressDialog.dismiss();
                    }
                }) {

            @Override
            protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
                try {
                    String jsonString = new String(response.data,
                            HttpHeaderParser.parseCharset(response.headers /**, PROTOCOL_CHARSET**/));
                    return Response.success(new JSONObject(jsonString),
                            HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                } catch (JSONException je) {
                    return Response.error(new ParseError(je));
                }
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/json");
                return headers;
            }
        };

        AppController.getInstance().addToRequestQueue(jsonObjectRequest, Constants.tag_json_obj);
    }
}

Full code here GitHub.