改进:如何用细分指定基本网址?

时间:2018-08-02 08:49:29

标签: android retrofit2 okhttp3

我想用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();

但是我使用每个网址的版本信息,例如: “ https://api-staging.xxxx.co/v1/login

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

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

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

非常感谢您!

3 个答案:

答案 0 :(得分:0)

u不应使用

  

.host(“ api-staging.xxxx.co/v1 /”)

主机只能是域名或IP地址。

您可以使用“ addPathSegment”方法添加细分,或这样写:

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

答案 1 :(得分:0)

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

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

然后我像这样使用它:

BuildConfig.BASE_URL

答案 2 :(得分:0)

  

但是我使用每个网址的版本信息,例如:   “ https://api-staging.xxxx.co/v1/login

如果要使用动态url,则可以构建另一个改造实例,这是个好方法。我曾经使用拦截器,但是当连续使用不同的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;
    }