Add dependency for Volley library in your build.gradle.
1 |
compile 'com.android.volley:volley:1.0.0' |
Volley is a network library which makes fast and easier to make HTTP Request for android application. Using Volley library we don’t need to create AsyncTask to make multiple API calls in volley there is RequestQueue where we can enqueue each request. Here in this example, We used Google place autocomplete API. We are going to make synchronous HTTP Request using volley. To make synchronous HTTP request make a RequestFuture object. And make JsonObjectRequest pass this parameter RequestMethod, URL, pass object of type Json and pass RequestFuture instance.
1 2 3 4 5 6 |
RequestFuture<JSONObject> requestFuture=RequestFuture.newFuture(); final String mURL = "https://maps.googleapis.com/maps/api/place/ autocomplete/json?key="+KEY+"&input=" + input; JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, mURL,new JSONObject(),requestFuture,requestFuture); MySingleton.getInstance(mContext).addToRequestQueue(request); |
Add your request in RequestQueue. Now, whenever the user makes an HTTP request each request added to RequestQueue.To get response object from the requestFuture we call get() method. And we also set a timeout of let’s say 10 seconds so we don’t block the UI thread indefinitely in case our request times out.
1 2 3 4 5 |
try { JSONObject object= requestFuture.get(10,TimeUnit.SECONDS); } catch (InterruptedException e|ExecutionException e|TimeoutException e) { e.printStackTrace(); } |
Hope this helps you to understand how we can use volley used to make the synchronous HTTP request.