Add Header to Retrofit Requests

Lending Square :

I have a token which i save to sharedPreferences and then i get that token and pass it as an authorization to a Retrofit requests. This is my codes below which i used to add a header to my retrofit requests.

I need to add the header below: "Authorization" "Bearer" + token

public static Retrofit getClient(String token) {

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient okClient = new OkHttpClient();

    Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
            .create();

    okClient.interceptors().add(chain -> {
        Response response = chain.proceed(chain.request());
        return response;
    });

    okClient.interceptors().add(chain -> {
        Request original = chain.request();
        Request request = original.newBuilder()
                .header("Authorization", token)
                .method(original.method(), original.body())
                .build();

        return chain.proceed(request);
    });

    okClient.interceptors().add(logging);

    if (retrofit==null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(Config.BASE_URL1)
                .client(okClient)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
    }
    return retrofit;
}

This how i send my token to the retrofit client

 Retrofit retrofit = RetrofitClient.getClient("Bearer" + " " +       authUser.getToken());
 APIService mAPIService = retrofit.create(APIService.class);

But unfortunately the server responds with the message no authorization

Nabin Bhandari :

You can send header to server without using an interceptor. Just add a field in your method declaration in your service interface like this:

@GET("my/orders/{id}")
Call<Order> getOrder(@Header("Authorization") String token,
                     @Path("id") int order_id);

Then create a Call object to send request as below:

APIService apiService= retrofit.create(APIService.class);
Call<Order> call = apiService.getOrder(token, id);
call.enqueue(/*callback*/);

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=477091&siteId=1