I'm building an Android app to that consumes a REST API. I'm using OkHttp and the API I'm hitting requires an API key. I thought it would be best practice to store my API key in my strings.xml file. I also thought it was a best practice to not include Android sdk specific code, now I'm realizing these two thoughts might be conflicting.
I'm building the app using an MVP architecture and in my NetModule class I have a method provideOkHttpClient(Cache) that looks like this:
@Provides
@Singleton
OkHttpClient provideOkhttpClient (Cache cache){
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.cache(cache);
// Add GiantBomb.com api key to request
client.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
HttpUrl originalHttpUrl = original.url();
HttpUrl url = originalHttpUrl.newBuilder()
.addQueryParameter("apikey", MY_API_KEY)
.build();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.url(url);
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
return client.build();
}
I got the Interceptor code from the "Add Query Parameters" section here
I'm wondering what the best way to store my API key is. This key should never change and since I'm only using a single website's API for this app right now it will be in all the requests. I did try to put the API key in my strings.xml but I do not have a Context available to call getString(). Of course I could just store the API key in a local string but I'm not sure that's the best method. Any help is appreciated!
Here is the full NetModule.java class in case it helps. Here I am trying to call the getString method, but there is no Context and I'm not sure I can even get a Context. If it's not already obvious, this is my first foray into MVP, and only my first Android app after taking Udacity's Developing Android Apps course.