手動

2016-08-03 5 views
2

現在、私のクライアントにのみ401応答の場合には、要求を認証し、認証を有効にする:手動

this.client.authenticator(new okhttp3.Authenticator() { 

     public Request authenticate(Route route, Response response) throws IOException { 
     String credentials = authenticator.getCredentials(); 
     if (credentials.equals(response.request().header("Authorization"))) { 
      throw new TraversonException(401, "Unauthorized", response.request().url().toString()); 
     } else { 
      defaultHeader("Authorization", credentials); 

      Request.Builder newRequest = response.request().newBuilder() 
           .headers(Headers.of(defaultHeaders)); 

      return newRequest.build(); 
     } 
}); 

しかし、私はこの動作を変更し、手動または自動最初の呼び出しごとにどちらかそれを呼び出すことができるようにしたいのですが?どういうわけか可能ですか?

答えて

2

認証が予想通りに必要であり、プロキシに関係しない場合は、Authenticatorの代わりにインターセプタを実装します。

OkHttpClient.Builder clientBuilder = ...; 
clientBuilder.networkInterceptors().add(0, myInterceptor); 
client = clientBuilder.build(); 

例インターセプタhttps://github.com/yschimke/oksocial/blob/master/src/main/java/com/baulsupp/oksocial/authenticator/ServiceInterceptor.java

n.b. https://github.com/square/okhttp/pull/2458にこのユースケースの可能なサポートに関する議論があります。現在のAuthenticator APIの1つの問題は、失敗した(401)要求からの応答を前提としていることです。

+0

また、今後のリリースでは先制型認証を実装したいと考えています。 –