我正在使用OkHttp3Retrofit2
需要用令牌代替所有请求。
我写了一个TokenAuthentificator类:

   public class TokenAuthenticator implements Authenticator {

        @Override
        public Request authenticate(Route route, okhttp3.Response response) throws IOException {
            return response.request().newBuilder()
                    .header(Const.Url.COOKIE, preferenceHelper.getToken())
                    .build();
        }
    }


并使用Retrofit初始化它:

@Inject
public RestApi(PreferenceHelper preferenceHelper) {
    TokenAuthenticator authenticator = new TokenAuthenticator();

    this.preferenceHelper = preferenceHelper;
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .authenticator(authenticator)
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();


    Retrofit retrofit = new Retrofit.Builder().baseUrl(Const.Url.API)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();
    user = retrofit.create(User.class);
}


但是,请求中的标头仍然没有被替换。
可能是什么问题呢?

请求示例:

 @Multipart
    @POST("user_set_photo")
    Observable<Response<TechmasResponse>> setPhoto(@Part("PERSONAL_PHOTO\"; filename=\"image.png\" ") RequestBody file);


在活动/片段中,如下所示:

Subscription request = restApi.user.setPhoto(body)
                .compose(RxUtils.applySchedulers())
                .subscribe(this::successAddPhoto, this::handleError);
        unSubscribeOnDestroy(request);

最佳答案

将令牌存储在SharedPrererences中,并从Interceptor加载它:

public class TokenAppendingHeaderInterceptor implements Interceptor {

    private TokenStorage tokenStorage;

    public TokenAppendingHeaderInterceptor(TokenStorage tokenStorage){
        this.tokenStorage = tokenStorage;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String token = tokenStorage.getToken();
        Request newRequest = request.newBuilder()
                .addHeader("Accept", "application/json")
                .addHeader("sessionId", token)
                .addHeader("application-type", "REST")
                .build();
        return chain.proceed(newRequest);
    }
}


对我有用

关于android - OkHttp身份验证器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43390146/

10-12 07:05