Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to externalise the Base URL in Retrofit for Android

We have an Android app now that are working fine using Retrofit. We are trying to automate the build for testing and production release, to reduce the chance of human error (i.e. dev forget to point the Base URL to production when build for production..etc)

I noticed that the Base URL for Retrofit are defined in the class file. Is there any method that we can use to configure it to be in a properties file or xml so that we can use the Gradle script to pick the right file to be included with the build?

Thank you

like image 665
ipohfly Avatar asked Apr 04 '19 14:04

ipohfly


People also ask

How do I change my retrofit base URL?

For default base url, Retrofit is injected with DEVELOPMENT_BASE_URL assuming default selection for application. Then, provide this interceptor to our OkHttpClient Builder like below. Now, We can INJECT HostSelectionInterceptor in our viewmodel or activity by simply providing @Inject annotation.

How do I find the URL of a base URL?

To find the base URL of your website, go to the site's front page. What you see in the address bar on your site's front page is the base URL of your website.

What is base URL in app?

The URL found in the address bar of the front page of a website is its base URL.

Can you use multiple Baseurl in retrofit?

Yes, you can create two different Service instances.


1 Answers

You can define a constant in your buildTypes:

buildTypes {
    debug {
        buildConfigField "String", "API_URL", "\"https://url/pre/\""
    }
    release {
        buildConfigField "String", "API_URL", "\"https://url/pro/\""
    }
}

And then use it in the retrofit builder:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BuildConfig.API_URL)
    .build();

Notice that if you have different modules the BuildConfig is defined in each of them. For this cases I define the buildTypes in the app module and pass the BuildConfig.API_URL as parameter in the call to the module with the retrofit builder.

like image 121
jeprubio Avatar answered Nov 09 '22 14:11

jeprubio