Home > Back-end >  How to change part of base url dynamically in retrofit android
How to change part of base url dynamically in retrofit android

Time:05-30

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.

CodePudding user response:

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.

CodePudding user response:

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);
}

}

  • Related