Andrew
Andrew

Reputation: 2157

Working with headers retrofit

I am working on application which is like a e-mail client, so I have to get a list of my new messages. For this task I have to use my access-token which I got previously during my autorization. I have my interface:

@Headers({"Content-type: application/json",
            "Authorization: Bearer my_token"})
    @GET("/v1/message/list")
    Call<MessageAnswer> getInMess(@Query("type") int type, @Query("offset") int offset);

and I have also my mainactivity.class with initialising the following interface:

public void info() {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://server/")
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    APIService mAPIService = retrofit.create(APIService.class);
    mAPIService.getInMess(1,1).enqueue(new Callback<MessageAnswer>() {
        @Override
        public void onResponse(@NonNull Call<MessageAnswer> call, @NonNull Response<MessageAnswer> response) {

        }

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

        }
    });
}

and I don't know how I can insert my token into my interface or somewhere else, because doing it by hand is too stupid I think. Maybe somebody know how to help me, so I will be happy for some useful advices.

Upvotes: 0

Views: 69

Answers (1)

Andrii Zhumela
Andrii Zhumela

Reputation: 70

Try to use requestInterceptor. Here are the sample:

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

httpClient.addInterceptor(new Interceptor() {

    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request original = chain.request();

        Request request = original.newBuilder()
            .header("User-Agent", "Your-App-Name")
            .header("Accept", "application/vnd.yourapi.v1.full+json")
            .method(original.method(), original.body())
            .build();

        return chain.proceed(request);
    }
}

OkHttpClient client = httpClient.build();

Retrofit retrofit = new Retrofit.Builder()  
    .baseUrl(API_BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .client(client)
    .build();

Upvotes: 1

Related Questions