简体   繁体   English

Retrofit如何设置baseUrl?

[英]How to set baseUrl in Retrofit?

I want to set the BaseUrl in Retrofit to change dynamically between stage and live because i have an app that has stage and live version.我想在 Retrofit 中设置 BaseUrl 以在舞台和现场之间动态更改,因为我有一个具有舞台和现场版本的应用程序。 So i made a spinner and the user can select either he wants.所以我做了一个微调器,用户可以 select 任意他想要的。 But the problem is that after the user select the flavor he wants and then wants to change again it doens't work because the baseUrl is not changing like it should be.但问题是,在用户 select 之后,他想要的味道然后想要再次改变它不起作用,因为 baseUrl 没有像它应该的那样改变。

I have this class where is defined the API_URL but it's not working:我有这个 class 定义了 API_URL 但它不起作用:

@Singleton
class SingleUrlApi {
    companion object{
        public var API_URL_STAGE = BuildConfig.STAGE
    }
}

and then i have another function that uses this API_URL_STAGE然后我有另一个使用此 API_URL_STAGE 的 function

 override fun getUrl(shopUrl: ShopUrl, vararg args: String): String {
        return when (shopUrl) {
            ShopUrl.API_BASE -> if (SingleUrlApi.API_URL_STAGE) {
                context.localizedContext(localeManager.getCurrentLocale()).getString(R.string.base_url_stage)
            } else {
                context.localizedContext(localeManager.getCurrentLocale()).getString(R.string.base_url_live)
            }
            ShopUrl.WEB_BASE -> if (SingleUrlApi.API_URL_STAGE) {
                context.localizedContext(localeManager.getCurrentLocale()).getString(R.string.base_web_url_stage)
            } else {
                context.localizedContext(localeManager.getCurrentLocale()).getString(R.string.base_web_url_live)
            }

You can use OkHttp along with Retrofit.您可以将 OkHttp 与 Retrofit 一起使用。 Then, you can use an OkHttpInterceptor to change the URL of the request然后,您可以使用OkHttpInterceptor更改请求的 URL

public final class HostSelectionInterceptor implements Interceptor {

  @Override public okhttp3.Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    String host = //logic to fetch the new URL
    if (host != null) {
      HttpUrl newUrl = request.url().newBuilder()
          .host(host)
          .build();
      request = request.newBuilder()
          .url(newUrl)
          .build();
    }
    return chain.proceed(request);
  }
}

An easy and effective way is to use this library: RetrofitUrlManager一个简单有效的方法是使用这个库: RetrofitUrlManager

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM