How to Use Interceptor to Add Headers in Retrofit 2.0

How to use interceptor to add Headers in Retrofit 2.0?

Check this out.

public class HeaderInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request()
.newBuilder()
.addHeader("appid", "hello")
.addHeader("deviceplatform", "android")
.removeHeader("User-Agent")
.addHeader("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0")
.build();
Response response = chain.proceed(request);
return response;
}
}

Kotlin

class HeaderInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response = chain.run {
proceed(
request()
.newBuilder()
.addHeader("appid", "hello")
.addHeader("deviceplatform", "android")
.removeHeader("User-Agent")
.addHeader("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0")
.build()
)
}
}

Retrofit 2.0 - Adding header does not work

I found solution to the issue I have been facing for long hours.

I made a silly mistake in the key name of header. It should be Authorization but was keeping it as token.

Thanks a lot for everyone who tried to help me out.

Android Retrofit 2.0 adding headers with interceptor doesn't work

The order you add the interceptors matters. Your logging interceptor runs first, and only after that is the header-adding interceptor run.

For best logging experience, make the logging interceptor the last one you add.

adding a header to all requests in the retrofit factory?

You can add multiple interceptors to your OkHttpClient.
It should something like this:
This is your logging interceptor:

    val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY

This is a header one

OkHttpClient.Builder().apply {
addInterceptor { chain ->
val request = chain.request()
val builder = request
.newBuilder()
.header("SOME", "SOME")
.method(request.method(), request.body())
val mutatedRequest = builder.build()
val response = chain.proceed(mutatedRequest)
response
}
addInterceptor(interceptor) // this is your http logging
}.build()

Change SOME and SOME with your preferred values.

Adding header to all request with Retrofit 2

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("parameter", "value").build();
return chain.proceed(request);
}
});
Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl(url).client(httpClient.build()).build();

how to solve add variable in Retrofit header on android studio

You need to create your own interceptor and add the token there not on your interface.

public class AuthorizationHeaderInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {

LoginResponse toc = LoginResponse();
Request request = chain.request()
.newBuilder()
.addHeader("Authorization", "Bearer " + toc.getToken())
.build();
Response response = chain.proceed(request);
return response;
}
}

Then add this interceptor in your OkHttpClient and then add that OkHttpClient to your Retrofit.

Retrofit 2 - Elegant way of adding headers in the api level

I came up with a very simple and elegant (in my opinion) solution to my problem, and probably for other scenarios.

I use the Headers annotation to pass my custom annotations, and since OkHttp requires that they follow the Name: Value format, I decided that my format will be: @: ANNOTATION_NAME.

So basically:

public interface MyApi {
@POST("register")
@HEADERS("@: NoAuth")
Call<RegisterResponse> register(@Body RegisterRequest data);

@GET("user/{userId}")
Call<GetUserResponse> getUser(@Path("userId") String userId);
}

Then I can intercept the request, check whether I have an annotation with name @. If so, I get the value and remove the header from the request.

This works well even if you want to have more than one "custom annotation":

@HEADERS({
"@: NoAuth",
"@: LogResponseCode"
})

Here's how to extract all of these "custom annotations" and remove them from the request:

new OkHttpClient.Builder().addNetworkInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();

List<String> customAnnotations = request.headers().values("@");

// do something with the "custom annotations"

request = request.newBuilder().removeHeader("@").build();
return chain.proceed(request);
}
});

Add Header Parameter in Retrofit

After trying a couple of times i figured out the answer.

The error

java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2 path $

was coming due the failure of parsing the json.

In the method call I was passing a String instead of a POJO class.

@Headers("user-key: 9900a9720d31dfd5fdb4352700c")
@GET("api/v2.1/search")
Call<String> getRestaurantsBySearch(@Query("entity_id") String entity_id, @Query("entity_type") String entity_type, @Query("q") String query);

I should have passed instead of Call<String> the type of Call<Data>

Data being the Pojo class

something like this

@Headers("user-key: 9900a9720d31dfd5fdb4352700c")
@GET("api/v2.1/search")
Call<Data> getRestaurantsBySearch(@Query("entity_id") String entity_id, @Query("entity_type") String entity_type, @Query("q") String query);


Related Topics



Leave a reply



Submit