我已经使用基础认证实现了Retrofit,我在登录请求中发送了@header,但是当我调用一些受授权的请求时,它返回401(未授权)。
如何通用地实现它?还是我总是需要在我的授权请求中调用@header?
@GET("user")
Call<User> getUserByEmail(@Query("email") String email, @Header("Authorization") String authorization);
当我调用“按电子邮件获取用户”时(我对用户进行身份验证)...
@PUT("usuario/{userId}/")
Call<User> putUserById(@Path("userId") Integer id, @Body User user);
当我调用Put user(我需要进行身份验证的请求)时。
我的Retrofit类...
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();
}
}
有人能帮我吗?