Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Header to Retrofit Requests

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

like image 244
Lending Square Avatar asked Aug 25 '17 15:08

Lending Square


People also ask

How do I add a header in OkHttp?

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.

How do I add basic authentication to retrofit?

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.


2 Answers

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*/);
like image 133
Nabin Bhandari Avatar answered Sep 26 '22 00:09

Nabin Bhandari


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 :)

like image 43
DalveerSinghDaiya Avatar answered Sep 24 '22 00:09

DalveerSinghDaiya