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();
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.
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);
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);
}
});
How to add header to retrofit response in Android
The first option to add a static header is to define the header and respective value for your API method as an annotation. The header gets automatically added by Retrofit for every request using this method. The annotation can be either key-value-pair as one string or as a list of strings.
The example above shows the key-value-definition for the static header:
Further, you can pass multiple key-value-strings as a list encapsulated in curly brackets {} to the @Headers annotation.
How you can pass multiple key-value-strings as a list encapsulated in curly brackets:
A more customizable approach are dynamic headers. A dynamic header is passed like a parameter to the method. The provided parameter value gets mapped by Retrofit before executing the request.
Define dynamic headers where you might pass different values for each request:
Happy Coding!! /p>
Adding header to retrofit call request
You can harcode any header value as follow
@POST("auth")
@Headers("Any value")
fun createLoginRequest(@Body credentials: Credentials): Observable<Response<User>>
For more info see this link
In your case, x-www-form-urlencoded request should be handled like in this example:
public interface TaskService {
@FormUrlEncoded
@POST("tasks")
Call<Task> createTask(@Field("title") String title);
}
Adding custom headers to every request in Kotlin okHttp retrofit2 using the current code
As per Retrofit documentation :
Interceptors can add, remove, or replace request headers.
Interceptor are used to manipulate outgoing request or the incoming response. In your case you have to add API_KEY to every request as header. That's where the interceptor can be handy. You can add header in the interceptor as below:
private val okHttpClient = OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
// Attempting to add headers to every request
.addInterceptor { chain ->
val request = chain.request().newBuilder()
.addHeader("x-api-key", BuildConfig.AWS_MICROSERVICES_API_KEY)
chain.proceed(request.build())
}
.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.
Related Topics
"Hello World" Android App with as Few Files as Possible, No Ide, and Text Editor Only
How to Update Xml File from Another Xml File Dynamically
Android (Java) Simple Send and Receive with Server - Fast Setup Challenge
Portrait for Phone, Landscape for Tablet (Android-Layout)
Values of Counter Changes After Scrolling Expendablelistview
Jruby: Watir Is Hanging When Launching Browser
Sending Variable from One Jsp to Another Jsp
Most Efficient Way to Cast List<Subclass> to List<Baseclass>
How to Find How Much Disk Space Is Left Using Java
How to Do an Https Post from Android
How to Wait for All Tasks in an Threadpoolexecutor to Finish Without Shutting Down the Executor
Get Button Coordinates and Detect If Finger Is Over Them - Android
Google Cloud Messaging: Don't Receive Alerts When iOS App Is in Background