【问题标题】:How to get res Strings.xml from a retrofit interface class?如何从改造接口类中获取 res Strings.xml?
【发布时间】:2021-02-14 23:25:21
【问题描述】:

我在res/strings.xml 中有一个字符串

<string name="clientId">dfgljkwm51</string>

我想在我的改造接口类中使用字符串:


public class RetrofitInterfaces {
        public interface GetAlbum{
             @Headers("Authorization: Client-ID " + clientId) //Want to use the String valye here.
             @GET
             Call<Feed> listRepos(@Url String url);
        }
}

这就是我使用改造电话的方式:

 private void makeNetworkCall(String url) {
        RetrofitInterfaces.GetAlbum service = RetrofitClientInstance.getRetrofitInstance()
                .create(RetrofitInterfaces.GetAlbum.class);
        Call<Feed> call = service.listRepos(url);
        call.enqueue(new Callback<Feed>() {
            . . . 
}

如何将此值传递给我的 Retrofit 接口类,以便我可以在标头中使用该值?

【问题讨论】:

    标签: android retrofit retrofit2


    【解决方案1】:

    strings.xml 用于本地化,您可能不应该使用它来存储 api 键值。

    您可以改用 BuildConfig 字段:

    buildConfigField "String", "API_KEY", '"key"'
    

    然后您可以使用BuildConfig.API_KEY 在任何地方访问它

    完整示例,在您的 Build.Gradle(:app) 中

    defaultConfig {
            applicationId "your app"
            minSdkVersion 21
            targetSdkVersion 30
            versionCode buildVersionCode
            versionName buildVersionName
            testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    
            buildConfigField "String", "API_KEY", '"api key here"'
        }
    

    BuildConfig 字段还有一个额外的好处,那就是在将源代码作为开源上传时提供了一种保护源代码安全的方法,by allowing you to read your key into a build config variable from an external file

    【讨论】:

    • 我找到了 BuildConfig 文件夹,但它显示“生成了“build”文件夹下的文件,不应编辑”。 i.imgur.com/uubkt1X.png
    • 您不应该也不能在其中添加或编辑任何内容,请在您的 build.gradle(:app) @DIRTYDAVE 中进行这些更改
    • 有趣的是,使用 buildConfigField 与上面的答案一样的常量类有什么优缺点? stackoverflow.com/a/64643448/11110509
    • here@DIRTYDAVE
    • 没关系,如果这是您要作为开源发布的项目,这不是正确的方法,您应该从文件中读取它,请参阅here。基本上,将密钥存储在一个文件中,并在使用 gradle 编译您的应用程序时从该文件中读取它,然后您不会发布包含您上传代码的密钥的文件,因此其他人没有它,但我们这里又跑题了:)
    【解决方案2】:

    为常量值创建一个类

    public class Constants {
    
    public static final String key = "as23rsffwr2";
    
    }
    

    这样访问

    Constants.key
    

    【讨论】:

    • 不是一个好的解决方案,糟糕的代码,而不是看到a_local_nobody的解决方案
    【解决方案3】:

    我会像Haseeb Mirza 提到的那样创建一个常量。当您需要在不同的环境中拥有不同的客户端 ID 时,构建配置字段会很有用。

    【讨论】:

    • 带有 buildconfig 字段,如果您要发布您的代码,您可以keep your key hidden,所以这是使用它的额外好处
    猜你喜欢
    • 2015-09-09
    • 1970-01-01
    • 2015-05-08
    • 2020-05-31
    • 1970-01-01
    • 2019-11-05
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多