简体   繁体   中英

Retrofit add header with token and id

I have a problem with getting authenticated user. Before it I got token and user id. Now i need to get user from server using access token and id. I have header format

Now I'am trying to add header with user token and id using interceptor.

My code:

Interceptor interceptor = new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request newRequest = chain.request().newBuilder()
                    .addHeader("Accept", "application/json")
                    .addHeader("authorization", token) <-??
                    .addHeader("driver_id", id) <-??
                    .build();
            return chain.proceed(newRequest);
        }
    };
    OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
    okHttpBuilder.addInterceptor(interceptor);
    OkHttpClient okHttpClient = okHttpBuilder.build();

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

Interface:

@GET("driver/v1/driver")
Call<Driver> getAuthorizedDriver();

Different variants throws 401 error, don't know what to do Log:

I/Response code: 401
I/Response message: Unauthorized`

I got it. It's must look like:

@GET("driver/v1/driver")
Call<Driver> getAuthorizedDriver(@Header("authorization") String auth);

And auth:

Call<Driver> call = apiInterface.getAuthorizedDriver("Token token=" + token + ", driver_id=" + id);

Try to pass the header values via the method call:

@GET("driver/v1/driver")
Call<Driver> getAuthorizedDriver(@Header("authorization") String token,
                                 @Header("driver_id") Integer id);

You also wouldn't have to deal with this huge chunk of Interceptor code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM