How to consume REST API in Android Studio using Volley?

How to consume REST API in Android Studio using Volley?

API is very useful while working on Web Application. The term API means the interface that consists of endpoints for a request. An API takes request from the client i.e. parameters or the input and processes them to produce desired outputs to give as response. We use APIs by invoking them from our client applications. In this article, I am going to show you how to call an API. We will be using volley library to achieve that. It can be implemented using different libraries also like HttpURLConnectionRetrofit etc. but I prefer to use Volley as it is easy to implement.

Add the INTERNET permission

To use Volley and send requests to API, you must add the android.permission.INTERNET permission to your app’s manifest. This allows your app to connect to the network.

VOLLEY IMPLEMENTATION

To use volley library with your android application, add dependency to your build.gradle(app level).

dependencies {
    ...
    compile 'com.android.volley:volley:1.0.0'
}

GET REQUEST

final TextView textView = (TextView) findViewById(R.id.text);
// ...

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // Display the first 500 characters of the response string.
        textView.setText("Response is: "+ response.substring(0,500));
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        textView.setText("That didn't work!");
    }
});

// Add the request to the RequestQueue.
queue.add(stringRequest);
168 Views
Written by
Nazal TK
Join the discussion

nazal.in

Instagram

Invalid username or token.