dev
dev

Reputation: 11

how to access api with api_key Using Retrofit

I am new on android.Can any one tell me how to add the header for api_key using retrofit.I am not able to understand how i can do this.

I find this code from net.where i have to put this code in android folder structure.I am confused with this.where i have to add api_key.

// Define the interceptor, add authentication headers
Interceptor interceptor = new Interceptor() {
  @Override
  public okhttp3.Response intercept(Chain chain) throws IOException {
    Request newRequest = chain.request().newBuilder().addHeader("User-Agent", "Retrofit-Sample-App").build();
    return chain.proceed(newRequest);
  }
};

// Add the interceptor to OkHttpClient
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.interceptors().add(interceptor);
OkHttpClient client = builder.build();

// Set the custom client when building adapter
Retrofit retrofit = new Retrofit.Builder()
  .baseUrl("https://api.github.com")
  .addConverterFactory(GsonConverterFactory.create())
  .client(client)
  .build();

Upvotes: 0

Views: 1393

Answers (1)

Nicola Gallazzi
Nicola Gallazzi

Reputation: 8713

You can store your api_key in your strings.xml file like this:

<string name="your_api_key_id" translatable="false">YOUR_API_KEY</string>

Then, in your OkHttpClient definition class, write a method to build your OkHttpClient like that:

private final static String API_KEY_IDENTIFIER = "key_identifier";

private OkHttpClient getHttpClient(){
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                HttpUrl originalUrl = original.url();
                HttpUrl url = originalUrl.newBuilder()
                        .addQueryParameter(API_KEY_IDENTIFIER, mContext.getString(R.string.your_api_key_id))
                        .build();
                Request.Builder requestBuilder = original.newBuilder().url(url);
                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        });
        return httpClient.build();
    }

You should implement your client builder class with Singleton pattern, in order to have the client build centralized in one place inside your code

Upvotes: 1

Related Questions