1

I want to pass Header and Body dynamically to a Web Api. So, I have implemented as below:

public interface NotificationService {
    @POST("user/update/notification")
    Call<JsonObject> notification(@Header("Authorization") String authorization, @Body NotificationRequest notificationRequest);
}

And using this as,

showProgressDialog();
NotificationRequest notificationRequest = new NotificationRequest(checked ? ApiConstants.IS_ON : ApiConstants.IS_OFF, getUserId());
NotificationService notificationService = ApiFactory.provideNotificationService();
Call<JsonObject> call = notificationService.notification(getAuthorizationHeader(), notificationRequest);
call.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                logDebug(SettingsFragment.class, response.body().toString());
                hideProgressDialog();
            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {
                hideProgressDialog();
            }
        });

But this way, I am not getting null response (response.body() is null).

Can anyone suggest how to pass Dynamic Header and Body together ?

Note: I went through this tutorial but didn't found the way to pass both.

Chintan Soni
  • 24,761
  • 25
  • 106
  • 174

2 Answers2

0

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));
Chintan Soni
  • 24,761
  • 25
  • 106
  • 174
0

You are using Retrofit2. It is completely possible using dynamic headers for example:

    @POST("hello-world")
    fun getKaboom(
        @Body body: TheBody,
        @Header("hello-world-header") helloWorldHeader: String? = "kaboom"
    ): Single<KaboomResponse>
ror
  • 3,295
  • 1
  • 19
  • 27