Skip to content Skip to sidebar Skip to footer

How To Define A Header To All Request Using Retrofit?

I'm looking for a solution to define a unique Header to use in all requests. Today I use @Header to each request did pass like parameter but I want define only header that works in

Solution 1:

Official document:

Headers that need to be added to every request can be specified using a RequestInterceptor. The following code creates a RequestInterceptor that will add a User-Agent header to every request.

RequestInterceptorrequestInterceptor=newRequestInterceptor() {
  @Overridepublicvoidintercept(RequestFacade request) {
    request.addHeader("User-Agent", "Retrofit-Sample-App");
  }
};

RestAdapterrestAdapter=newRestAdapter.Builder()
.setEndpoint("https://api.github.com")
.setRequestInterceptor(requestInterceptor)
.build();

Solution 2:

In Retrofit 2, you need to intercept the request on the network layer provided by OkHttp

OkHttpClient.BuilderhttpClient=newOkHttpClient.Builder();  
httpClient.addInterceptor(newInterceptor() {  
@Overridepublic Response intercept(Interceptor.Chain chain)throws IOException {
    Requestoriginal= chain.request();

    Requestrequest= original.newBuilder()
        .header("User-Agent", "Your-App-Name")
        .header("Accept", "application/vnd.yourapi.v1.full+json")
        .method(original.method(), original.body())
        .build();

    return chain.proceed(request);
   }
}

OkHttpClientclient= httpClient.build();  
Retrofitretrofit=newRetrofit.Builder()  
    .baseUrl(API_BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .client(client)
    .build();

Check this, it explains the differences very well.

Solution 3:

Depending on your OkHttp lib:

OkHttpClienthttpClient=newOkHttpClient();
httpClient.networkInterceptors().add(newInterceptor() {
    @Overridepublic Response intercept(Chain chain)throws IOException {
        Requestrequest= chain.request().newBuilder().addHeader("User-Agent", System.getProperty("http.agent")).build();
        return chain.proceed(request);
    }
});
Retrofitretrofit=newRetrofit.Builder()  
    .baseUrl(API_BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .client(httpClient)
    .build();

Solution 4:

As the other answers have described, you need a RequestInterceptor. Luckily, this interface has a single method, so Java 8 and above will treat it as a functional interface and let you implement it with a lambda. Simple!

For example, if you're wrapping a specific API and need a header for each endpoint, you might do this when you build your adapter:

RestAdapterwhatever=newRestAdapter.Builder().setEndpoint(endpoint)
                                                .setRequestInterceptor(r -> r.addHeader("X-Special-Vendor-Header", "2.0.0"))
                                                .build()

Solution 5:

Here's the solution for adding header using retrofit 2.1. We need to add interceptor

public OkHttpClient getHeader(final String authorizationValue ) {
        HttpLoggingInterceptorinterceptor=newHttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClientokClient=newOkHttpClient.Builder()
                .addInterceptor(interceptor)
                .addNetworkInterceptor(
                        newInterceptor() {
                            @Overridepublic Response intercept(Interceptor.Chain chain)throws IOException {
                                Requestrequest=null;
                                if (authorizationValue != null) {
                                    Log.d("--Authorization-- ", authorizationValue);

                                    Requestoriginal= chain.request();
                                    // Request customization: add request headers
                                    Request.BuilderrequestBuilder= original.newBuilder()
                                            .addHeader("Authorization", authorizationValue);

                                    request = requestBuilder.build();
                                }
                                return chain.proceed(request);
                            }
                        })
                .build();
        return okClient;

    }

Now in your retrofit object add this header in the client

Retrofitretrofit=newRetrofit.Builder()
                .baseUrl(url)
                .client(getHeader(authorizationValue))
                .addConverterFactory(GsonConverterFactory.create())
                .build();

Post a Comment for "How To Define A Header To All Request Using Retrofit?"