0

I want to change part of base url at run time based on site selected by user. How this can be achieved using retrofit.

For eg. Base URL : https://{siteCode}.prod.com/ where siteCode will be site selected by user at run time.

Currenly I have fixed base url in build.gradle.

 production {
            versionNameSuffix "-prod"

            buildConfigField "String", "BASE_URL", "\"https://vh.prod.com/\""
        }

How this can be made dynamic using retrofit.

Ragini
  • 765
  • 1
  • 11
  • 29
  • Currently there is no way to change URL dynamically. The only way you can do that is by creating different Retrofit instances. – Vaibhav Goyal May 30 '22 at 05:31
  • You will have to save siteCode to shared prefs and create new retrofit instance everytime use changes siteCode – Harsh Kanjariya May 30 '22 at 05:54
  • Does this answer your question? [Retrofit - Change BaseUrl](https://stackoverflow.com/questions/38805689/retrofit-change-baseurl) – Radhey May 30 '22 at 06:24

2 Answers2

2

You can use the @Url annotation to pass a complete URL for an endpoint.

@GET
suspend fun getData(@Url String url): ResponseBody

The @Url parameter will replace the baseUrl set while creating the Retrofit instance.

Arpit Shukla
  • 9,612
  • 1
  • 14
  • 40
0

this is possible using retrofit interceptor, you can use multiple base url ..

public class HostSelectionInterceptor implements Interceptor {
private volatile String host;

public void setHost(String host) {
    this.host = HttpUrl.parse(host).host();
}

@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    String reqUrl = request.url().host();

    String host = this.host;
    if (host != null) {
        HttpUrl newUrl = request.url().newBuilder()
            .host(host)
            .build();
        request = request.newBuilder()
            .url(newUrl)
            .build();
    }
    return chain.proceed(request);
}

}