OkHttp Interceptor for Retrofit2 | With Example

This tutorial only focuses on OkHttp Interceptor. If you want to learn how to send a network request with Retrofit from basics read this

In our last post we have learnt how to send a network request with Retrofit on Android. While Retrofit makes sending HTTP requests quite simple it also allows a unique mechanism to monitor and rewrite these requests. This is implemented with the help of OkHttp Interceptor. Intercept – the word means “to obstruct something from reaching its destinations”, similarly Interceptors obstruct a request, rewrite it and then send it to the destinations(server). For example suppose you need all the HTTP requests sent from your app to have authorization token as header. Instead of dynamically adding the same header to all the endpoints as shown here you can simply add a interceptor which will be invoked every time you send a request.

The official explanation for Interceptors is

Interceptors are to observe, modify and potentially short-circuits requests going out and the corresponding responses coming back in. Typically interceptors add, remove, or transform headers on the request  or response.

Interceptors are basically of two types

  • Application Interceptors
    These are high level interceptors which are used to intercept request and response. They are usually used to rewrite headers/query of both request and response. These are definitly invoked once even if the response is fetched from cache.
  • Network Interceptors
    These are low level interceptors used to monitor requested just as it is transmitted over the network. Are very useful to follow redirects and retries and give access to various low level details of the request. These are not invoked if the response is cached.

The diagram below explains the difference between Network and Application Interceptors

interceptors.png

Creating Interceptors

Creating or defining a Interceptor is very simple. You just need to implement the Interceptor interface and override the intercept() method as shown below.  The same interface implementation works for both  NetworkInterceptor and ApplicationInterceptor

private static class CustomInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        /*
        chain.request() returns original request that you can work with(modify, rewrite)
        */
        Request request = chain.request();

        // Here you can rewrite the request

        /*
        chain.proceed(request) is the call which will initiate the HTTP work. This call invokes the
        request and returns the response as per the request.
        */
        Response response = chain.proceed(request);

        //Here you can rewrite/modify the response

        return response;
    }
}

 

A call to chain.proceed(request) is a critical part of each interceptor’s implementation. This simple-looking method is where all the HTTP work happens, this is where the request is initiated and a response is fetched to satisfy the request.

Once you have defined your interface you can register it with the OkHttp client as shown below. Now you should register this client with Retrofit.Builder thereby for all your requests OkHttp client will be used and your interceptor will be invoked

OkHttpClient okHttpClient = new OkHttpClient.Builder()
    .addInterceptor(new CustomInterceptor()) // This is used to add ApplicationInterceptor.
    .addNetworkInterceptor(new CustomInterceptor()) //This is used to add NetworkInterceptor.
    .build();

//Defining the Retrofit using Builder
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL) //This is the onlt mandatory call on Builder object.
    .client(okHttpClient) //The Htttp client to be used for requests
    .addConverterFactory(GsonConverterFactory.create()) // Convertor library used to convert response into POJO
    .build();

 

 

Logging Request and Response

As developers it is very important that we log the requests/responses which are sent and received  from the app. These logs give us details about the headers, response body, request body and various other details which are crucial for debugging any error. Thanks to Interceptors logging all the HTTP operations on Android is very simple.

Retrofit provides us with a Custom Interceptor – HttpLoggingInterceptor which can be registered with OkHttpClient. With this you will be able to print all the logs for the HTTP operations through this client.

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://backend.example.com")
        .client(client)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

 

Rewriting Requests- Adding/Removing Headers

We have already seen how to define a Custom Interceptor. Now in this section we will define a Custom Interceptor to modify the headers sent with a network request.

private static class RequestInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        /*
        chain.request() returns original request that you can work with(modify, rewrite)
        */
        Request originalRequest = chain.request();

        Headers headers = new Headers.Builder()
            .add("Authorization", "auth-value")
            .add("User-Agent", "you-app-name")
            .build();

        Request newRequest = originalRequest.newBuilder()
            .addHeader("Authorization", "auth-value") //Adds a header with name and value.
            .addHeader("User-Agent", "you-app-name")
            .cacheControl(CacheControl.FORCE_CACHE) // Sets this request's Cache-Control header, replacing any cache control headers already present.
            .headers(headers) //Removes all headers on this builder and adds headers.
            .method(originalRequest.method(), null) // Adds request method and request body
            .removeHeader("Authorization") // Removes all the headers with this name
            .build();

        /*
        chain.proceed(request) is the call which will initiate the HTTP work. This call invokes the
        request and returns the response as per the request.
        */
        Response response = chain.proceed(newRequest);

        return response;
    }

}

 

Rewriting Response with OKHttp Interceptor

Similarly, OkHttp Interceptor can be used to rewrite/ modify response from the server. With this you can not only rewrite response headers but also can make changes to the response body.

In the example below we read the response code and build a new response body based on the response code.

private static class ResponseInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        // We obtain the response using chain.proceed() API. This invokes the request and return the response
        Response response = chain.proceed(chain.request());
        try {

            JSONObject jsonObject = new JSONObject();

            if (response.code() == 200) {
                jsonObject.put("code", 200);
                jsonObject.put("status", "OK");
                jsonObject.put("message", new JSONObject(response.body().string()));
            } else {
                jsonObject.put("code", 404);
                jsonObject.put("status", "ERROR");
                jsonObject.put("message", new JSONObject(response.body().string()));
            }
            MediaType contentType = response.body().contentType();
            ResponseBody body = ResponseBody.create(contentType, jsonObject.toString());
            return response.newBuilder().body(body).build();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return response;
    }
}

Android Image Upload Example | Multipart Retrofit2

This tutorial only discusses Android image upload using multipart with Retrofit2. If you want to learn about sending HTTP requests using Retrofit2 from basics read this.

Why use Multipart to Upload Image ?

Before diving deep into Android Image upload, its important to understand some basics of HTTP requests. Most importantly how are different types of data sent to server. POST requests are used to send data to server, this data can either be simple readable text fields or sometimes even non alphanumeric binary data(like image files).  In our last tutorial6 we saw how to send a simple POST request with retrofit. To facilitate sending different types of data we have different methods given below

With application/x-www-form-urlencoded, the body of the HTTP message sent to the server is essentially one giant query string — name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). But for each non-alphanumeric byte that exists in one of our values, it’s going to take three bytes to represent it. This is very inefficient for sending large files hence this method cannot be used for sending image files

That’s where  multipart/form-data  comes in. Multipart sends a single object(file) in various parts, each part is separated by a boundary and has some portion of object’s data. Each part also has its own headers like Content-Type, Content-Deposition. Below is a sample representation of multipart request to upload two file a.txt and a.html

POST / HTTP/1.1
[[ Less interesting headers ... ]]
Content-Type: multipart/form-data; boundary=---------------------------735323031399963166993862150
Content-Length: 834

-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="text1"

text default
-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="text2"

aωb
-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="file3"; filename="binary"
Content-Type: application/octet-stream

aωb
-----------------------------735323031399963166993862150--

 

This efficiency of sending single file in multiple parts is the reason most of the browsers use Multipart to upload files. Retrofit is one of the few network libraries which has built in support for Multipart. This enables you  to upload any files from your app without worrying of any of the internal details of Multipart.

Android Image Upload

In the following example we will be uploading a Image file to Server using Multipart with Retrofit2. As per the scope of this example we will only cover how to upload a image/file on server but if you want to first learn how to pick image from gallery/camera please read this example

Step 1 : Add Gradle dependencies

implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

Step 2 : Create Retrofit Instance

Create a class NetworkClient.java  to retrieve the Retrofit object anywhere in your application. This instance will be used to send the HTTP request from your app.

public class NetworkClient {

    private static final String BASE_URL = "";
    private static Retrofit retrofit;

    public static Retrofit getRetrofitClient(Context context) {

        if (retrofit == null) {
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .build();
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

        }

        return retrofit;
    }
    
}

Step 3 : Define the Upload API

We know that with Retrofit2, interface methods are used to  define the APIs with which the app will be interacting. Therefore for uploading an image we define the following API. Note the use of @Multipart and @Part

ublic interface UploadAPIs {
    @Multipart
    @POST("/upload")
    Call<ResponseBody> uploadImage(@Part MultipartBody.Part file, @Part("name") RequestBody requestBody);
}

 

@Multipart 
Denotes that the request body is multi-part. Parts should be declared as parameters and annotated with @Part.

@Part
This denotes a single part of Multipart request. The parameter on which this type exists will be processed in three ways

  • If the parameter type is MultipartBody.Part the contents will be used directly. Part name is not required with the annotation (i.e., @Part MultipartBody.Part part).
  • If the parameter  type is RequestBody the value will be used directly with its content type. Supply the part name in the annotation (e.g., @Part("foo") RequestBody foo).
  • Other object types will be converted to an appropriate representation by using a converter. Supply the part name in the annotation (e.g., @Part("foo") Image photo).

 

Step 4 : Uploading an Image

Now comes most important part- Uploading a File. Input parameter to this method is a simple image file path. As already mentioned if you want to learn how to get file path of the images from gallery/camera read this tutorial

  • Using the file path we create a file object and then create a request body with that image file. Now with the request body we create a MultipartBody.Part by passing file name and part name as shown in the snippet below. This MultipartBody.Part is sent to Retrofit to initiate image upload
  • We can even send some text fields along with the image. Make sure server is able to handle all tha parts that you are sending. Since this is a demo example I am just sending a sample description text request body along with the image.
  • Both  the text and image are sent as parts along with the mutipart requests

 

private void uploadToServer(String filePath) {
     Retrofit retrofit = NetworkClient.getRetrofitClient(this);

     UploadAPIs uploadAPIs = retrofit.create(UploadAPIs.class);

     //Create a file object using file path
     File file = new File(filePath);

     // Create a request body with file and image media type
     RequestBody fileReqBody = RequestBody.create(MediaType.parse("image/*"), file);

     // Create MultipartBody.Part using file request-body,file name and part name 
     MultipartBody.Part part = MultipartBody.Part.createFormData("upload", file.getName(), fileReqBody);

     //Create request body with text description and text media type
     RequestBody description = RequestBody.create(MediaType.parse("text/plain"), "image-type");

     // 
     Call call = uploadAPIs.uploadImage(part, description);

     call.enqueue(new Callback() {
         @Override
         public void onResponse(Call call, Response response) {

         }

         @Override
         public void onFailure(Call call, Throwable t) {

         }
     });

 }

Conclusion

This finishes our fully functional Android Image Upload Example, but in software development just getting something working is not enough. One of the major characteristic of a good programmer is that he writes clean code. And the best tips and guidelines for clean code are mentioned in this book by noted software expert Robert C. Martin. It is a must read for every software engineer.


If you are new to Android you should definitely go through the list of Android examples here. It is a must read for every Android Developer
sexy Indian girls

Android DownloadManager Example [Complete Tutorial]

We have a separate tutorial section on this website for HTTP operations. Over there we have already covered all the different network operations like sending a GET/POST request, uploading images, logging request, adding headers etc. We have used two of the most popular Libraries- Volley and Retrofit which provide complete support for all these network operations. But when it comes to downloading large files you cant use Retrofit or Volley, both of these recommend using DownloadManager. And that is what today’s tutorial is all about – DownloadManager Example

The DownloadManager is a system service that handles long-running HTTP downloads. Clients may request that a URI be downloaded to a particular destination file.

Here are some advantages of using DownloadManager

  • It performs all the HTTP interaction on background thread by default. You dont need to create any thread.
  • It gracefully handles connectivity issues if the network changes or device reboots by automatically retrying download after failure due to any reason.
  • It provides features like pause/ resume download thereby improving user experience.
  • Has a in built mechanism  to inform the user of download progress using notification.

Downloading a File

In this section of DownloadManager Example we will prepare our download request and initiate the File Download  

Add Permissions

First step in this DownloadManager Example is to add INTERNET permission to the AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

Create Activity

We need to create only one Activity in this DownloadManager Example which will have a button to initiate the download of file. Following is the layout file for this activity

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.irshadkumail.downloadexample.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:id="@+id/download"
        android:text="DOWNLOAD"
        android:layout_centerInParent="true"
        android:layout_height="wrap_content" />


</RelativeLayout>

Now in our Java file of the Activity we initialize the button and set up a click listener as shown below

public class MainActivity extends AppCompatActivity {

    private Button button;

    private long downloadID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button=findViewById(R.id.download);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });
    }
}
  • Note that we have also created a global long variable which will be used to store download identifier id. More about this in next section

Prepare the DownloadManager.Request

Before starting the download we need to create a  DownloadManager.Request object with all the details of the download and conditions to start it. DownloadManager.Request has provided us with multiple APIs to set information necessary to begin the download. The only mandatory information to start a download is network URI. Even if you have not specified any destination, Android stores the downloaded file in a shared storage . Below code snippet shows how we prepare our DownloadManager.Request with all the details.

       File file=new File(getExternalFilesDir(null),"Dummy");
       /*
       Create a DownloadManager.Request with all the information necessary to start the download
        */

       DownloadManager.Request request=new DownloadManager.Request(Uri.parse("http://speedtest.ftp.otenet.gr/files/test10Mb.db"))
               .setTitle("Dummy File")// Title of the Download Notification
               .setDescription("Downloading")// Description of the Download Notification
               .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)// Visibility of the download Notification
               .setDestinationUri(Uri.fromFile(file))// Uri of the destination file
               .setRequiresCharging(false)// Set if charging is required to begin the download
               .setAllowedOverMetered(true)// Set if download is allowed on Mobile network
               .setAllowedOverRoaming(true);// Set if download is allowed on roaming network

     
   

Following are some important APIs used to set information of the download

  • setNotificationVisibility(int)
    This API is to control whether a system notification is shown while this download is running or when it is completed.
    It can takes any of the following predefined values: 
    #VISIBILITY_HIDDEN
    #VISIBILITY_VISIBLE 
    #VISIBILITY_VISIBLE_NOTIFY_COMPLETED
    If set to VISIBILITY_HIDDEN, this requires the permission android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
  •  setDescription(String), setTitle(String)
    These APIs are used to set the description and title of the download notification (if displayed).
  • setDestinationInExternalFilesDir(Context ,String,String) , setDestinationUri(Uri), setDestinationInExternalPublicDir(String,String)
    These APIs are used to set the destination file path of the downloaded file. You can start a download even without specifying the destination, in which case file is temporarily stored in shared storage. Also if you are storing the file in external storage you need to add STORAGE permissions in the Manifest.
  • addRequestHeader(String,String)
    This API is used to add a request header to the HTTP request used to download the file

Apart from these they are a lot of other APIs like setAllowedOverRoaming(), setRequiresCharging(), setAllowedOverMetered()  etc which define the conditions for the download to start. We have not used all the APIs in this DownloadManager Example but you can read more about them here.

Initiate the download

Once the DownloadManager.Request is ready with all the information you can start the download as shown in snippet below

DownloadManager downloadManager= (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
downloadID = downloadManager.enqueue(request);// enqueue puts the download request in the queue.
  • enqueue(request) returns  a unique long ID which acts as an identifier for the download. Note that calling enqueue() doesnt necessarily start the download immediately. It rather schedules the download request in a queue. Once the DownloadManager is free is starts the download.
  • Important thing to note is how we initialize global variable downloadID . enqueue() returns an ID for the download, unique across the system. Global variable downloadID is used to store this ID. It is used to reference this download in future.

Listen to Download Complete

So far in this DownloadManager Example we saw to initiate downloading a file in Android. This section covers how to be notified when your download is completed.

One thing to note is that DownloadManager  is a separate system service which downloads files requested by client. Here your app is the client and once you call enqueue() from your app it is now the responsibility of DownloadManager to schedule that download and save the file at destination. Therefore it is important that the client is informed when the download is completed. Android DownloadManager sends a ACTION_DOWNLOAD_COMPLETE broadcast intent when any download is completed. You can listen for this broadcast using a BroadcastReceiver and identify if your download is completed using the unique long ID returned by enqueue().

Not sure what Broadcast is and How does BroadcastReceiver work?  Read this simple tutorial

You can be notified when your download is complete by following three steps

  • Create a BroadcastReceiver as shown in snippet below.Inside the receiver we just check if the received broadcast is for our download by matching the received download id with our enqueued download.
    private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
           @Override
           public void onReceive(Context context, Intent intent) {
    
               //Fetching the download id received with the broadcast
               long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
    
               //Checking if the received broadcast is for our enqueued download by matching download id
               if (downloadID == id) {
                   Toast.makeText(MainActivity.this, "Download Completed", Toast.LENGTH_SHORT).show();
               }
    
           }
       };
  • Once the BroadcastReceiver is created you can register for ACTION_DOWNLOAD_COMPLETE in the onCreate method of your activity. This ACTION_DOWNLOAD_COMPLETE broadcast is fired everytime any file download is completed by DownloadManager.
    @Override
       protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);
    
           button=findViewById(R.id.download);
           registerReceiver(onDownloadComplete,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
           button.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View view) {
                   beginDownload();
               }
           });
       }
  • It is also important that you unregister the BroadcastReceiver in onDestroy. This ensures you only listen for this broadcast as long as the activity is active
    @Override
      public void onDestroy() {
          super.onDestroy();
          unregisterReceiver(onDownloadComplete);
      }
    

     

DownloadManager Example: Complete Code

This completes DownloadManager Example. Below is the complete code of your Activity

public class MainActivity extends AppCompatActivity {

    private Button button;

    private long downloadID;

    private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            //Fetching the download id received with the broadcast
            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);

            //Checking if the received broadcast is for our enqueued download by matching download id
            if (downloadID == id) {
                Toast.makeText(MainActivity.this, "Download Completed", Toast.LENGTH_SHORT).show();
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button=findViewById(R.id.download);
        registerReceiver(onDownloadComplete,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                beginDownload();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(onDownloadComplete);
    }

    private void beginDownload(){

        File file=new File(getExternalFilesDir(null),"Dummy");
        /*
        Create a DownloadManager.Request with all the information necessary to start the download
         */

        DownloadManager.Request request=new DownloadManager.Request(Uri.parse("http://speedtest.ftp.otenet.gr/files/test10Mb.db"))
                .setTitle("Dummy File")// Title of the Download Notification
                .setDescription("Downloading")// Description of the Download Notification
                .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)// Visibility of the download Notification
                .setDestinationUri(Uri.fromFile(file))// Uri of the destination file
                .setRequiresCharging(false)// Set if charging is required to begin the download
                .setAllowedOverMetered(true)// Set if download is allowed on Mobile network
                .setAllowedOverRoaming(true);// Set if download is allowed on roaming network

        DownloadManager downloadManager= (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        downloadID = downloadManager.enqueue(request);// enqueue puts the download request in the queue.
    }


}

 

We hope you are now clear on how to download files on Android. You can even learn how to upload files on Android by reading this simple tutorial

Android Example : HTTP GET, POST Request with Retrofit

In our last tutorial we discussed about how to send a network request using Volley Library, while Volley is a widely used network library for basic HTTP operations there is one more library which is quite popular among Android developers- Retrofit. In fact many developers prefer Retrofit over Volley due to its ease of use, performance, extensibility etc.

Retrofit is basically an HTTP client for Android and Java developed by the awesome folks at Square. What makes it unique is that with Retrofit you don’t need to worry about parsing the response – meaning de-serialization is handled in the background itself, you just need to configure any convertor library (GSON, Jackson etc). Retrofit uses OkHttp by default for HTTP operations.

In this example we will develop an application which will send a network request with Retrofit and display the response. We will be using OpenWeather API to fetch current weather details. Its a free API service which provider number of APIs to fetch weather details anywhere on the Globe, you just need to register to obtain the API key. Read this for more

API:
https://api.openweathermap.org/data/2.5/weather?q=London,uk

Continue reading

Retrofit Android Example : Sending HTTP GET, POST Request

In our last tutorial we discussed about how to send a network request using Volley Library, while Volley is a widely used network library for basic HTTP operations there is one more library which is quite popular among Android developers- Retrofit. In fact many developers prefer Retrofit over Volley due to its ease of use, performance, extensibility etc.

Retrofit is basically an HTTP client for Android and Java developed by the awesome folks at Square. It uses OKHttp by default for network operations. What makes it unique is that with Retrofit you don’t need to worry about parsing the response – meaning de-serialization is handled in the background itself. You just need to configure any convertor library (GSON, Jackson etc) and the job is done.

In this example we will develop an application which will send a network request with Retrofit and display the response. We will be using OpenWeather API to fetch current weather details. Its a free API service which provides a number of APIs to fetch weather details anywhere on the Globe. You just need to register to obtain the API key. Read this for more

API:
https://api.openweathermap.org/data/2.5/weather?q=London,uk

Continue reading

Android Volley Custom Request-Java Object as Response

This example is for sending a Custom Request in Volley. If you are new to Volley and want to learn how to send a simple GET, POST request in Volley read this

I always have preferred Volley library over Retrofit for sending network requests in an Android Application mostly because of its cache handling  and request prioritization. But many Retrofit users argue that one of the biggest advantage with Retrofit is that it automatically parses the json/xml response not knowing that the same could be done with Volley.  You already know that Volley provides inbuilt support which will gives us response in any of these three formats

  • String
  • JSONObject
  • JSONArray

Now using a custom request with the help of Gson you can directly receive response in the form of POJO- Java Objects

Continue reading

Android Volley Example- HTTP GET,POST with Custom Headers

Nowadays almost every app is required to send a network request. And for a beginner in android development sending a network request should be one the first concepts he should learn.

In Android all time-consuming tasks (like a network request) are to be performed on the background thread. While developing Java Application you must have used  HttpsUrlConnection to send network request. In Android sending requests using HttpsURLConnection that too on a background thread and then sending the response back on the  main thread might make you believe that performing network operations is very complicated in Android. Fortunately Android Volley has made it pretty simple.

android_volley_example

What is Android Volley

Volley is a HTTP library used for performing network requests in Android. It is quite popular among Android developers reason being that it moves all the complicated stuff under the hood and makes sending a network request ridiculously easy. Following are the things volley takes care of on its own

Continue reading