【问题标题】:Retrofit: how can I specify the baseurl with a segment?改造:如何指定带有段的baseurl?
【发布时间】:2018-08-02 08:49:28
【问题描述】:

我想用HttpUrl对象测试初始化​​Retrofit的baseurl:

HttpUrl baseUrl = new HttpUrl.Builder()
                    .scheme("https")
                    .host("api-staging.xxxx.co")
                    .build();

            mRetrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .client(httpClient.build())
                    .build();

但我为每个 url 使用版本信息,例如: "https://api-staging.xxxx.co/v1/login"

所以我想在这个配置中指定版本。所以我尝试这样:

  • .host("api-staging.xxxx.co/v1/") > 崩溃

而且我不想在每个 WS(映射)上添加版本,那么我该如何正确地做到这一点呢?

非常感谢!

【问题讨论】:

  • 是否必须在运行时添加版本?
  • @Dracarys:不,没必要

标签: android retrofit2 okhttp3


【解决方案1】:

你不应该使用

.host("api-staging.xxxx.co/v1/")

主机可以是域名或IP地址。

你可以使用“addPathSegment”方法添加段,或者这样写:

new Retrofit.Builder().baseUrl("api-staging.xxxx.co/v1/")

【讨论】:

  • 只用.baseUrl(String base) 一定有用
【解决方案2】:

但我为每个 url 使用版本信息,例如: "https://api-staging.xxxx.co/v1/login"

如果你想使用动态url,你可以构建另一个retrofit实例,这是个好方法。我曾经使用拦截器,但是当连续调用很多具有不同 url 的 api 时,这不是一个好方法(它调用了错误的 url) 你可以这样使用:

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

【讨论】:

    【解决方案3】:

    我不确定这是否是你想要的,但我通常会在我的模块的 build.gradle 中声明基本 URL:

    android {
    ...
        defaultConfig {
        ...
            buildConfigField("String", "BASE_URL", "\"https://api-staging.xxxx.co/v1/login\"")
        }
    }
    

    然后我像这样使用它:

    BuildConfig.BASE_URL
    

    【讨论】:

      猜你喜欢
      • 2016-12-12
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-23
      相关资源
      最近更新 更多