1

I'm using Retrofit2 to consume the json. when I do login a bearer token is generated and saved into SharedPrefenences. I want to use this bearer token as Authentication header. and everytime I used it the response message was "Unauthorized"

 here's my Request: 

                @GET("user/wishlist")
       Call<WishListModel> getWishList(@Header("Authorization") String BearerToken);

and here's the call:

      Retrofit retrofit = new Retrofit.Builder().baseUrl("URL").addConverterFactory(GsonConverterFactory.create()).build();
      RequestInterface requestInterface = retrofit.create(RequestInterface.class);
      Call<WishListModel> call = requestInterface.getWishList("Bearer "+token);
  • requestInterface.getWishList("Bearer "+token);// why are you concatenating? is "Bearer" part of the token? – shb Sep 27 '18 at 17:39
  • Possible duplicate of [Adding header to all request with Retrofit 2](https://stackoverflow.com/questions/32605711/adding-header-to-all-request-with-retrofit-2) – Gokul Nath KP Sep 27 '18 at 17:46

1 Answers1

4

You need to add header using OkHttp interceptor.

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();

Then use the retrofit instance to invoke your call.

Please refer Adding header to all request with Retrofit 2

Gokul Nath KP
  • 15,485
  • 24
  • 88
  • 126