Retrofit - Change BaseUrl

I have a scenario where I need to call an API with the same BaseUrl, for example. www.myAPI.com , but with a different baseUrl .

I have an instance of Retrofit 2 that is built through Builder :

return new Retrofit.Builder().baseUrl(FlavourConstants.BASE_URL).addConverterFactory(GsonConverterFactory.create(gson)).client(okHttpClient).build();

FlavourConstants.BASE_URL as follows:

public static final String BASE_URL = "http://myApi.development:5000/api/v1/";

For some WebRequests I have to call the same API, but in other cases I have to call it a completely different baseUrl . How to change a Retrofit instance to point to a different url at runtime?

There is no .setBaseUrl or setter Retrofit .setBaseUrl or anything similar as it was built using Builder .

Any ideas?

+23
android retrofit
source share
7 answers

Luckily for you, Upgrading has a simple solution for this:

 public interface UserManager { @GET public Call<ResponseBody> userName(@Url String url); } 

The url string must indicate the full URL that you want to use.

+19
source share

I just used the function below when I ran into this problem. but I was in a hurry, and I believe that I should use another, and I used "retrofit2: retrofit: 2.0.2"

 public static Retrofit getClient(String baseURL) { if (retrofit == null) { retrofit = new Retrofit.Builder() .baseUrl(baseURL) .addConverterFactory(GsonConverterFactory.create()) .build(); } else { if (!retrofit.baseUrl().equals(baseURL)) { retrofit = new Retrofit.Builder() .baseUrl(baseURL) .addConverterFactory(GsonConverterFactory.create()) .build(); } } return retrofit; } 

[ Update ] I found this link explaining @Url, which can be sent as a parameter, and I believe that it is more professional than my old solution. Please find below script:

  interface APIService{ @POST Call<AuthenticationResponse> login(@Url String loginUrl,[other parameters]) } 

And below is a method in a class that provides a modified object

 public static Retrofit getClient() { if (retrofit==null) { retrofit = new Retrofit.Builder() .baseUrl("http://baseurl.com") // example url .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; } 

Then you can call the method as shown below:

  APIInterface apiInterface = ApiClient.getClient2().create(ApiInterface.class); apiInterface.login("http://tempURL.com").enqueue(......); 
+4
source share

The easiest (but not the most efficient) way to change the base URL of Retrofit2 at runtime is to rebuild the modification instance with a new URL:

 private Retrofit retrofitInstance = Retrofit.Builder().baseUrl(FlavourConstants.BASE_URL).addConverterFactory(GsonConverterFactory.create(gson)).client(okHttpClient).build(); public void setNewBaseUrl(String url) { retrofitInstance = new Retrofit.Builder() .baseUrl(url) .addConverterFactory(GsonConverterFactory.create(gson)) .client(okHttpClient).build(); } ... retrofitInstance.create(ApiService.class); 

Alternatively, if you use OkHttp with Retrofit, you can add an OkHttp interceptor, like this one when creating the OkHttp client:

 HostSelectionInterceptor hostInterceptor = new HostSelectionInterceptor(); hostInterceptor.setHost(newBaseUrl); return new OkHttpClient.Builder() .addInterceptor(hostInterceptor) .build(); 
+3
source share

Retrofit 2.4, May 2019

Two simple solutions to this problem:

  1. Hard code for the new URL, leaving the base URL as it is:

     @GET("http://example.com/api/") Call<JSONObject> callMethodName(); 
  2. Pass the new URL as an argument, leaving the base URL as it is:

     @GET Call<JSONObject> callMethodName(@Url String url); 

Note: these methods work for GET or POST. However, this solution is only effective if you need to use an exception from one or two URLs other than the base. Otherwise, everything may become a little messy in terms of code accuracy.

If your project requires fully dynamically generated base URLs, then you can start reading this .

+2
source share

Well, if I'm not mistaken, Retrofit docs say that you can point to a different URL if you simply add the full ws URL to your servicse interface, which is different from BASE_URL in Retrofit Builder. One example ...

 public interface UserManager { @GET("put here ur entire url of the service") public Call<ResponseBody> getSomeStuff(); } 
+1
source share

There is also such a hack in Kotlin when determining the base URL

eg,

 @FormUrlEncoded @Headers("Accept: application/json") @POST suspend fun login( baseUrl: String, @Field("login") login: String, @Field("password") password: String @Url url: String = "$baseUrl/auth" ): ResponseAuth 

This does not work . Throws:

 java.lang.IllegalArgumentException: No Retrofit annotation found. (parameter #1) 

The only way suggested by Jake Wharton https://github.com/square/retrofit/issues/2161#issuecomment-274204152

 Retrofit.Builder() .baseUrl("https://localhost/") .create(ServerApi::class.java) 
 class DomainInterceptor : Interceptor { @Throws(Exception::class) override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() return chain.proceed( request.newBuilder() .url( request.url.toString() .replace("localhost", "yourdomain.com:80") .toHttpUrlOrNull() ?: request.url ) .build() ) } } 
+1
source share

The solution is to have two separate modification instances, one for your base URL FLAVORED and one for the other base URL.

So, just define two functions:

  public Retrofit getFlavouredInstance() { return new Retrofit.Builder().baseUrl(FlavourConstants.BASE_URL).addConverterFactory(GsonConverterFactory.create(gson)).client(okHttpClient).build(); } public Retrofit getOtherBaseUrl() { return Retrofit.Builder().baseUrl(OTHER_BASE_URL).addConverterFactory(GsonConverterFactory.create(gson)).client(okHttpClient).build(); } 

and after you just need to use the correct one.

0
source share

All Articles