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
Adds a header with name and value. Prefer this method for multiply-valued headers like "Cookie". Note that for some headers including Content-Length and Content-Encoding, OkHttp may replace value with a header derived from the request body.
Approach. You will have to create a Request interceptor ( BasicAuthInterceptor ) which extends Interceptor class of OkHttp library. Then, override intercept function and add your credentials into the request. Generate basic credentials with Credentials class of package OkHttp by using its basic function.
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*/);
Add a method in the BaseCaller Class for your headers like below:
public HashMap<String, String> getHeaders() {
HashMap<String, String> headerHashMap = new HashMap<>();
headerHashMap.put("Content-Type", "application/x-www-form-urlencoded");
headerHashMap.put("time_zone_name", DateTimeHelper.getTimeZoneName());
headerHashMap.put("gmt_offset", DateTimeHelper.getGMTOffset());
return headerHashMap;
}
Now create a method in your service class for url like :
@FormUrlEncoded
@POST("switch_user")
Call<JsonObject> switchUser(@HeaderMap Map<String, String> headers, @FieldMap Map<String, String> fields);
Finally in your class caller class call the methods as follows :
call = loginService.switchUser(getHeaders(), apiParams.mHashMap);
This will do the needful :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With