Retrofit 2 : REST Client for Android

Using RxJava with Retrofit

Add the following dependencies in Module level build.gradle file:

dependencies {

   /// ...
    // Add Retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    // Using gson as converter
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    // A Converter which supports converting strings and both primitives and their boxed types to text/plain bodies.
    implementation 'com.squareup.retrofit2:converter-scalars:2.5.0'

    implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
    // Because RxAndroid releases are few and far between, it is recommended you also
    // explicitly depend on RxJava's latest version for bug fixes and new features.
    // (see for latest 2.x.x version)
    implementation 'io.reactivex.rxjava2:rxjava:2.2.8'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'

    implementation 'com.squareup.okhttp3:logging-interceptor:3.14.0'
    androidTestImplementation ''
    testImplementation 'androidx.test:runner:1.3.0-alpha02'

Create an interface called with the following lines:

interface ApiService {

    @Headers("Content-Type: application/json")
    fun uploadGlucose(@Body str:String): Call<String>

    @Headers("Content-Type: application/json")
    fun uploadGlucose2(@Body str:String): Observable<String>

In your Activity file(or wherever you want to make the API call), add the following lines:

Retrofit retrofit = new Retrofit.Builder()
                .client(new OkHttpClient())

        ApiService service = retrofit.create(ApiService.class);
String str = "{}"; // Sending empty JSON as Request body.

Observable<String> call = service.uploadGlucose2(str);
                .subscribe(new Observer<String>() {
                    public void onSubscribe(Disposable d) {
                        Log.d(TAG, "onSubscribe: " + d.isDisposed());

                    public void onNext(String s) {
                        // Main Data is produced here.
                        Log.d(TAG, "onNext: " + s);

                    public void onError(Throwable e) {
                        Log.d(TAG, "onError: " + e.getMessage());

                    public void onComplete() {
                        Log.d(TAG, "onComplete: ");

You can now run the app and see the Log output from the Run tab as shown below:

In Postman the response looks like the following:

Suggested Reading:


Popular posts from this blog

ADB Cheat Sheet

Capturing Screen of Android Device using ADB

Enabling Internet in Android Emulator