Android Volley Tutorial and Examples.

 

1. How to make a HTTP GET and POST request in Volley

First you have to add Volley as an implementation statement in your app level build.gradle.

Please search for the latest version:

implementation 'com.android.volley:volley:1.0.0'

(a). MyApplication

Let’s start by creating an Application class. Here you can see we have the TAG as well as the RequestQueue defined as static fields.

Then in the onCreate() method we initialize our Volley using the Volley.newRequestQueue() method.

We have also defined a static method to retrieve the the RequestQueue instance.

import android.app.Application;

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

public class MyApplication extends Application{
    private static final String TAG = "MyApplication";

    public static RequestQueue sRequestQueue;

    @Override
    public void onCreate() {
        super.onCreate();

        sRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    public static RequestQueue getHttpQueues(){
        return sRequestQueue;
    }
}

(b). Constants

Then a class to have your constants:

public class Constant {

    public static final String JUHE_URL_GET = "http://apis.juhe.cn/mobile/get?phone=13429667914&key=562609042fbd47baa063b1a2c4637758";
    public static final String JUHE_URL_POST = "http://apis.juhe.cn/mobile/get?";
    public static final String JUHE_API_KEY = "562609042fbd47baa063b1a2c4637758";
    public static final String VOLLEY_TAG = "volley_tag";
}

(c). VolleyInterface

Then we create an abstract method with several methods and our Listeners:

import android.content.Context;

import com.android.volley.Response;
import com.android.volley.VolleyError;

public abstract class VolleyInterface {

    public Context mContext;
    public static Response.Listener sListener;
    public static Response.ErrorListener sErrorListener;

    public VolleyInterface(Context context, Response.Listener<String> listener, Response.ErrorListener errorListener) {
        this.mContext = context;
        this.sListener = listener;
        this.sErrorListener = errorListener;
    }
    public Response.Listener<String> loadingListener() {
        sListener = new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                onMySuccess(response.toString());
            }
        };
        return sListener;
    }

    public Response.ErrorListener errorListener(){
        sErrorListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                onMyError(error);
            }
        };
        return sErrorListener;
    }

    public abstract void onMySuccess(String result);
    public abstract void onMyError(VolleyError error);
}

(d). VolleyRequest

Then we can have our VolleyRequest class:

import android.content.Context;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.toolbox.StringRequest;
import com.example.innf.volleydemo.VolleyInterface;
import com.example.innf.volleydemo.app.MyApplication;

import java.util.Map;

public class VolleyRequest {
    private static final String TAG = "VolleyRequest";

    public static StringRequest sStringRequest;

    public static Context sContext;

    public static void RequestGet(Context context, String url, String tag, VolleyInterface volleyInterface) {
        MyApplication.getHttpQueues().cancelAll(tag); /
        sStringRequest = new StringRequest(Request.Method.GET, url, volleyInterface.loadingListener(), volleyInterface.errorListener());
        sStringRequest.setTag(tag);
        MyApplication.getHttpQueues().add(sStringRequest);
        MyApplication.getHttpQueues().start();
    }
    public static void RequestPost(Context context, String url, String tag, Map<String, String> params, VolleyInterface volleyInterface) {
        MyApplication.getHttpQueues().cancelAll(tag);
        sStringRequest = new StringRequest(url, volleyInterface.loadingListener(), volleyInterface.errorListener()){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return super.getParams();
            }
        };
        sStringRequest.setTag(tag);
        MyApplication.getHttpQueues().add(sStringRequest);
        MyApplication.getHttpQueues().start();
    }
}

(e). MainActivity

First you create your activity with some constants:

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private static final String STRING_GET_TAG = "string_get";
    private static final String STRING_POST_TAG = "string_post";
    private static final String JSON_OBJECT_GET_TAG = "json_object_get";
    private static final String JSON_OBJECT_POST_TAG = "json_object_post";
    private String tag = "";
    .......

Then:

1. How to perform a HTTP GET String request

You can see we are using the StringRequest class.

    private String volleyGetStringRequest() {
        StringRequest request = new StringRequest(Request.Method.GET, Constant.JUHE_URL_GET,
                new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
            }
        },
                new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
            }
        });
        request.setTag(STRING_GET_TAG);
        MyApplication.getHttpQueues().add(request);
        return request.getTag().toString();
    }

2. How to perform a HTTP GET Object request

This time round we use the JsonObjectRequest class. We will show the response or error in the Toast message.

    private String volleyGetJsonObjectRequest() {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, Constant.JUHE_URL_GET, null, 
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Toast.makeText(MainActivity.this, response.toString(), Toast.LENGTH_SHORT).show();
                    }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
                    }
            });
        request.setTag(JSON_OBJECT_GET_TAG);
        MyApplication.getHttpQueues().add(request);
        return request.getTag().toString();
    }

3. Making a Custom GET Request

    private void volleyRequestGetByCustom() {
        VolleyRequest.RequestGet(this, Constant.JUHE_URL_GET, STRING_GET_TAG, new VolleyInterface(this, VolleyInterface.sListener, VolleyInterface.sErrorListener) {
            @Override
            public void onMySuccess(String result) {
                Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
                Log.i(TAG, result);
            }

            @Override
            public void onMyError(VolleyError error) {
                Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }

4. How to make a HTTP String POST Request

Let’s make a HTTP POST request using the StringRequest:

    private String volleyPostStringRequest() {
        StringRequest request = new StringRequest(Request.Method.POST, Constant.JUHE_URL_POST,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
                    }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
                    }
                }){

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> hashMap = new HashMap<>();
                hashMap.put("phone", "13429667914");
                hashMap.put("key", "562609042fbd47baa063b1a2c4637758");
                return hashMap;
            }
        };
        request.setTag(STRING_POST_TAG);
        MyApplication.getHttpQueues().add(request);
        return request.getTag().toString();
    }

4. How to make a custom HTTP JSONObject POST Request

We now make a HTTP POST request using the JsonObjectRequest:

   private String volleyGetJsonObjectRequest() {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, Constant.JUHE_URL_GET, null, 
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Toast.makeText(MainActivity.this, response.toString(), Toast.LENGTH_SHORT).show();
                    }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
                    }
            });
        request.setTag(JSON_OBJECT_GET_TAG);
        MyApplication.getHttpQueues().add(request);
        return request.getTag().toString();
    }

Add all the above code in the main activity. Then add also your onCreate() and onPost() methods:

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        tag = volleyGetStringRequest();       
//        tag = volleyGetJsonObjectRequest();  
          tag = volleyPostStringRequest();        
//        tag = volleyPostJsonObjectRequest();    
//        volleyRequestGetByCustom();

    }
    @Override
    protected void onStop() {
        super.onStop();
        // cancelAll() 
        MyApplication.getHttpQueues().cancelAll(tag);
    }
}