Upload a file by using retrofit in android

In this tutorial, we will learn how to upload a file on the server by using Retrofit.  Retrofit is the most popular for networking API call. It is very simple and cleaner way API call in the Android application. Retrofit used OkHttp request call which is extended and customized of Http request.

Android developers love this because it is pretty simple and easy to integrate into an android application.  Retrofit is not only simple to integrate but also provide many features for handling multiple requests like Dispatcher, caching, and easy to handle the error.  Great 🙂

Retrofit works very seamlessly with RxJava. RxAndroid provides the Android Scheduler for scheduling the main thread switch between the threads easily. Now a day Reactive is getting popular in android application development. Android developers love this because it gives a really good response to become your app reactive.

Please check this post to understand that how to use API call by using retrofit in Kotlin? Please check these post of reactive nature to better understand. RxJava2 in Android Part-1, RxJava in Android part-2 and Understanding Java 8 Stream and RxJava2 Observable in Android.

Ok, Let’s see how to upload an image file to the server by using retrofit? First of all, we need to add the retrofit dependency file in your app grade file.

Now you need to create an input model class for image upload and for the retrofit response we need to create image output model class. Why is POJO class for the response which is given by server? The server gives the response in the format of JSON. But Retrofit internally used GSON Library to convert JSON format to plain Java object class.

Here is the get response model.

Now you need to create APIClient class to get an instance of Retrofit.

Here is the interface API service to execute the network call. For image upload, Retrofit is using multipart concept.

Let’s create a method to upload an image by retrofit.

Ok, Great 🙂 we have done well so for then good to go for upload. Now let’s call to image upload method.

Wrapping Up: As we practiced that retrofit is very simple and easy to integrate into Android for building awesome Android apps. It will work seamlessly with all design pattern in android. Here is the tutorial to learn how to use Retrofit in MVP design pattern with Kotlin?

Please do subscribe your email to get every newsletter from this blog and if you feel that this post helps you then do not forget to share and comment below.

You can learn all articles of MobologicPlus from the android app, which is available to download below.

Happy Coding 🙂

One thought on “Upload a file by using retrofit in android

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.