如何在 Retrofit for Android 中外部化 Base URL [英] How to externalise the Base URL in Retrofit for Android

查看:58
本文介绍了如何在 Retrofit for Android 中外部化 Base URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们现在有一个使用 Retrofit 运行良好的 Android 应用.我们正在尝试自动化构建以进行测试和生产发布,以减少人为错误的机会(即开发人员在为生产构建时忘记将基本 URL 指向生产......等)

We have an Android app now that are working fine using Retrofit. We are trying to automate the build for testing and production release, to reduce the chance of human error (i.e. dev forget to point the Base URL to production when build for production..etc)

我注意到 Retrofit 的 Base URL 是在类文件中定义的.有没有什么方法可以让我们将其配置在属性文件或 xml 中,以便我们可以使用 Gradle 脚本来选择要包含在构建中的正确文件?

I noticed that the Base URL for Retrofit are defined in the class file. Is there any method that we can use to configure it to be in a properties file or xml so that we can use the Gradle script to pick the right file to be included with the build?

谢谢

推荐答案

您可以在 buildTypes 中定义一个常量:

You can define a constant in your buildTypes:

buildTypes {
    debug {
        buildConfigField "String", "API_URL", "\"https://url/pre/\""
    }
    release {
        buildConfigField "String", "API_URL", "\"https://url/pro/\""
    }
}

然后在改造构建器中使用它:

And then use it in the retrofit builder:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BuildConfig.API_URL)
    .build();

请注意,如果您有不同的模块,则在每个模块中都定义了 BuildConfig.对于这种情况,我在应用模块中定义了 buildTypes,并在调用带有改造构建器的模块时将 BuildConfig.API_URL 作为参数传递.

Notice that if you have different modules the BuildConfig is defined in each of them. For this cases I define the buildTypes in the app module and pass the BuildConfig.API_URL as parameter in the call to the module with the retrofit builder.

这篇关于如何在 Retrofit for Android 中外部化 Base URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆