如何从改造界面class获取resStrings.xml?
How to get res Strings.xml from a retrofit interface class?
我在 res/strings.xml
中有一个字符串
<string name="clientId">dfgljkwm51</string>
我想在改造界面中使用字符串 class:
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 接口 class 以便我可以在 headers 中使用该值?
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 字段还有一个额外的好处,即在将源代码作为开源代码上传时提供一种保护源代码安全的方法,
为常量值制作一个class
public class Constants {
public static final String key = "as23rsffwr2";
}
这样访问
Constants.key
我会像 Haseeb Mirza 提到的那样创建一个常量。当您需要在不同的环境中使用不同的客户端 ID 时,构建配置字段会很有用。
我在 res/strings.xml
<string name="clientId">dfgljkwm51</string>
我想在改造界面中使用字符串 class:
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 接口 class 以便我可以在 headers 中使用该值?
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 字段还有一个额外的好处,即在将源代码作为开源代码上传时提供一种保护源代码安全的方法,
为常量值制作一个class
public class Constants {
public static final String key = "as23rsffwr2";
}
这样访问
Constants.key
我会像 Haseeb Mirza 提到的那样创建一个常量。当您需要在不同的环境中使用不同的客户端 ID 时,构建配置字段会很有用。