Search code examples
javaandroidretrofit2

How do I add bearer token to a form data using retrofit to POST to a web API


I am new to retrofit and also a little rusty in Java. I am trying to post a form data using retrofit to post it to a web service using an API. The API requires a Bearer token to Authenticate and accept the Data. The problem is that I don't know how to go about it. Below is my code.

My ApiClient.java class

public class ApiClient {

    private static Retrofit getRetrofit(){

        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);


        OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
            @NotNull
            @Override
            public Response intercept(@NotNull Chain chain) throws IOException {
                Request request=chain.request().newBuilder()
                        .addHeader("Authorization", "Bearer ")
                        .build();
                return chain.proceed(request);
            }
        }).addInterceptor(httpLoggingInterceptor)
                .build();


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

        return retrofit;
    }

    public static UserService getUserService(){
        UserService userService = getRetrofit().create(UserService.class);

        return userService;
    }
}

This is my UserService.java

public interface UserService {

    @POST("algonapi/api/enroll_vehicle")
    Call<UserResponse> saveUser(@Body UserRequest userRequest);

}

With the above code I get the response of 'Unauthenticated' in my logcat.

My Log

I/okhttp.OkHttpClient: date: Mon, 14 Jun 2021 19:52:40 GMT
    content-type: application/json
    x-powered-by: PHP/7.4.20
    cache-control: private, must-revalidate
    x-ratelimit-limit: 60
    x-ratelimit-remaining: 59
    pragma: no-cache
    expires: -1
I/okhttp.OkHttpClient: vary: Authorization
I/okhttp.OkHttpClient: {"message":"Unauthenticated."}

I need help


Solution

  • You haven't pass the token in addHeader("Authorization", "Bearer "). It should be

    @NotNull
            @Override
            public Response intercept(@NotNull Chain chain) throws IOException {
                String token = pref.getToken();
                Request request=chain.request().newBuilder()
                        .addHeader("Authorization", "Bearer " + token)
                        .build();
                return chain.proceed(request);
            }
    

    Also you are logging only body in logging interceptor. Try to remove this line httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);