Skip to content Skip to sidebar Skip to footer

Adding Authorization Header Interface Android Retrofit

I'm using retrofit library for solving my tasks connected with requests to server. I have got parameters from server developers: URL https://server/v1/message/list Edit this sectio

Solution 1:

Use this class and add header as per you need in addHeader() method.

public class ApiClient {

    private static Retrofit retrofit;
        public static Retrofit addHeader() {
            OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                    .connectTimeout(40, TimeUnit.SECONDS)
                    .readTimeout(40, TimeUnit.SECONDS)
                    .writeTimeout(40, TimeUnit.SECONDS)
                    .addInterceptor(new Interceptor() {
                        @Override
                        public Response intercept(Interceptor.Chain chain) throws IOException {
                            Request original = chain.request();
                            Request request = original.newBuilder()
                                    .header("Key", "Value")
                                    .header("Key", "Value")
                                    .method(original.method(), original.body())
                                    .build();

                            return chain.proceed(request);
                        }
                    })
                    .build();

            retrofit = new Retrofit.Builder()
                    .baseUrl("Your Base Url")
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(okHttpClient)
                    .build();
            return retrofit;
        }
}

and use it like this in your activity or fragment

APIService mAPIService = ApiClient.addHeader().create(APIService.class);
Call<List<MessageIN>> listCall = mAPIService.getInMess();
    listCall.enqueue(new Callback<List<MessageIN>>() {
        @Override
        public void onResponse(@NonNull Call<List<MessageIN>> call, @NonNull Response<List<MessageIN>> response) {

        }

        @Override
        public void onFailure(@NonNull Call<List<MessageIN>> call, @NonNull Throwable t) {

        }
    });

Post a Comment for "Adding Authorization Header Interface Android Retrofit"