I've implemented retrofit with basic authentication, I send the @header on my login request but when i call some authenticated request it returns me 401 (Not authorizated).
How I implement it generic? Or i always need to call my authenticated requests with @header?
@GET("user")
Call<User> getUserByEmail(@Query("email") String email, @Header("Authorization") String authorization);
When i call Get User By Email (I authenticate the user)...
@PUT("usuario/{userId}/")
Call<User> putUserById(@Path("userId") Integer id, @Body User user);
When i call Put user ( i need to make an authenticated request).
My retrofit class...
public class NetworkService {
private NetworkAPI networkAPI;
private OkHttpClient okHttpClient;
public NetworkService() {
okHttpClient = buildClient();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.HOST)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
networkAPI = retrofit.create(NetworkAPI.class);
}
public NetworkAPI getAPI() {
return networkAPI;
}
private OkHttpClient buildClient() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
return response;
}
});
builder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
//this is where we will add whatever we want to our request headers.
Request request = chain.request().newBuilder()
.addHeader("Accept", "application/json")
.addHeader("Content-Type", "application/json")
.build();
return chain.proceed(request);
}
});
return builder.build();
}
}
Can someone help me?
use @Header("Authorization") String authorization in NetworkService
Request request = chain.request().newBuilder()
.addHeader("Accept", "application/json")
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "AuthorizationValue")
.build();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With