How to Dynamically Set Headers in Retrofit (Android)

How to dynamically set headers in Retrofit (Android)

Since Retrofit 2.0 you have two options


1) Using OkHttp 2.2+ use Interceptor

At the Http level, you have more control over the request, so you could do things like applying headers only to a specific request made to a specific endpoint, and so on.

public class MyOkHttpInterceptor implements Interceptor {

@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
if (!"/posts".contains(originalRequest.url()) ) {
return chain.proceed(originalRequest);
}

String token = // get token logic

Request newRequest = originalRequest.newBuilder()
.header("X-Authorization", token)
.build();

return chain.proceed(newRequest);
}

[...]

OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.networkInterceptors().add(new MyOkHttpInterceptor());
OkClient okClient = new OkClient(okHttpClient);
YourApi api = new RestAdapter.Builder()
.setEndpoint(url)
.setClient(okClient)
.build()
.create(YourApi.class);

Edit:
Adding @JakeWarthon comment as another option as is also valid.

2) Put @Header on a method parameter and pass it as a value when invoking.

From the docs:

// Replaces the header with the the value of its target.
@GET("/")
void foo(@Header("Accept-Language") String lang, Callback<Response> cb);

Header parameters may be null which will omit them from the request. Passing a List or array will result in a header for each non-null item.

Note: Headers do not overwrite each other. All headers with the same name will be included in the request.


EDIT: This option should not be considered as Retrofit 2.* dropped support for interceptors.

3) User retrofit RequestInterceptor

From the docs:
Intercept every request before it is executed in order to add additional data.

You could do something like

public class MyRetrofitInterceptor implements RequestInterceptor {

@Override
public void intercept(RequestFacade req) {
String token = // get token logic
if (token != null) {
req.addHeader("X-Authorization", token);
}
}

[...]

YourApi api = new RestAdapter.Builder()
.setEndpoint(url)
.setRequestInterceptor(new MyRetrofitInterceptor())
.build()
.create(YourApi.class);

The "problem" with this approach is that the interceptor will get executed on all the endpoints, as it's set at the RestAdapter level, and not per endpoint. Also, the RequestFacade doesn't expose much information about the request, so no chance to add much logic around it.

retrofit 2 : pass dynamic header along with body

As far as I can see, there is no way to pass both Header and Body at the same time.

But You can add Interceptor into OkHttpClient as below:

OkHttpClient.Builder builder = new OkHttpClient.Builder()
.cache(cache);
builder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder ongoing = chain.request().newBuilder();
ongoing.addHeader("Authorization", getToken(app));
return chain.proceed(ongoing.build());
}
});

This will add authorization header in every request. You can control adding header to some condition like if User is logged in, only then request header should be added.

Just wrap below line in if condition to something like:

if(isUserLoggedIn())
ongoing.addHeader("Authorization", getToken(app));

Add Dynamic Header and Body in retrofit request

You should intercept your requests and add the token in the header. Retrofit also supports re-authenticating, in case your token expires (which it should).
The following tutorial has all you need: Retrofit — Token Authentication on Android

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.

Android Retrofit Setting Header Value Dynamically

The header type of param in imageUpload() is STRING, you just need fill a String header.

Call<ResponseBody> call = apiService.imageUpload(mPreferences.getString("accesstoken", ""), 
RequestBody.create(type,mPreferences.getString("UserName", "")),RequestBody.create(type,imagepath), RequestBody.create(type,action));


Related Topics



Leave a reply



Submit