2015-09-16 86 views
55

Retrofit 2's documentation所有請求說:添加報頭以與改造2

集管需要被添加到每一個請求可以使用OkHttp攔截器來指定。

它可以很容易地使用以前的版本,here's相關的QA。

但使用改造2,我找不到像setRequestInterceptorsetInterceptor方法,可以應用於Retrofit.Builder對象。

此外,似乎OkHttp中沒有RequestInterceptor了。改造的文件指我們Interceptor,我不太明白如何使用它爲此目的。

我該怎麼做?

回答

102
OkHttpClient httpClient = new OkHttpClient.Builder(); 

httpClient.addInterceptor(new Interceptor() { 
    @Override 
    public Response intercept(Chain chain) throws IOException { 
     Request request = chain.request().newBuilder().addHeader("parameter", "value").build(); 
     return chain.proceed(request); 
    } 
}); 
Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl(url).client(httpClient.build()).build(); 
+5

在retrofit2-beta3版本中,它有點不同。看到這裏:http://stackoverflow.com/questions/34973432/okhttpclient-throws-exception-after-upgrading-to-okhttp3 –

+0

我們如何確認這些頭被髮送。當我調用Call'enqueue'時,我看不到默認頭文件。 – viper

+0

它應該是'新的OkHttpClient.Builder()'而不是'新的OkHttpClient()' – Wojtek

46

最新翻新版本HERE - > 2.1.0。

拉姆達版本:

builder.addInterceptor(chain -> { 
    Request request = chain.request().newBuilder().addHeader("key", "value").build(); 
    return chain.proceed(request); 
    }); 

醜陋的長版:

builder.addInterceptor(new Interceptor() { 
    @Override public Response intercept(Chain chain) throws IOException { 
     Request request = chain.request().newBuilder().addHeader("key", "value").build(); 
     return chain.proceed(request); 
    } 
    }); 

完整版本:

class Factory { 

public static APIService create(Context context) { 

    OkHttpClient.Builder builder = new OkHttpClient().newBuilder(); 
    builder.readTimeout(10, TimeUnit.SECONDS); 
    builder.connectTimeout(5, TimeUnit.SECONDS); 

    if (BuildConfig.DEBUG) { 
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); 
    interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC); 
    builder.addInterceptor(interceptor); 
    } 

    builder.addInterceptor(chain -> { 
    Request request = chain.request().newBuilder().addHeader("key", "value").build(); 
    return chain.proceed(request); 
    }); 

    builder.addInterceptor(new UnauthorisedInterceptor(context)); 
    OkHttpClient client = builder.build(); 

    Retrofit retrofit = 
     new Retrofit.Builder().baseUrl(APIService.ENDPOINT).client(client).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build(); 

    return retrofit.create(APIService.class); 
    } 
} 

gradle這個文件(你需要,如果你打算使用它來添加日誌記錄攔截):

//----- Retrofit 
    compile 'com.squareup.retrofit2:retrofit:2.1.0' 
    compile "com.squareup.retrofit2:converter-gson:2.1.0" 
    compile "com.squareup.retrofit2:adapter-rxjava:2.1.0" 
    compile 'com.squareup.okhttp3:logging-interceptor:3.4.0' 
2

在我的情況addInterceptor()沒有工作到HTTP標頭添加到我的請求,我不得不使用addNetworkInterceptor()。代碼如下:

OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); 
httpClient.addNetworkInterceptor(new AddHeaderInterceptor()); 

而且攔截代碼:

public class AddHeaderInterceptor implements Interceptor { 
    @Override 
    public Response intercept(Chain chain) throws IOException { 

     Request.Builder builder = chain.request().newBuilder(); 
     builder.addHeader("Authorization", "MyauthHeaderContent"); 

     return chain.proceed(builder.build()); 
    } 
} 

這和更多的例子在this gist

9

用於記錄您的請求和響應,你需要一個攔截器,並設置頁眉你需要一個攔截器,下面是使用改進來一次性添加攔截器的解決方案2.1

public OkHttpClient getHeader(final String authorizationValue) { 
     HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); 
     interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); 
     OkHttpClient okClient = new OkHttpClient.Builder() 
       .addInterceptor(interceptor) 
       .addNetworkInterceptor(
         new Interceptor() { 
          @Override 
          public Response intercept(Interceptor.Chain chain) throws IOException { 
           Request request = null; 
           if (authorizationValue != null) { 
            Log.d("--Authorization-- ", authorizationValue); 

            Request original = chain.request(); 
            // Request customization: add request headers 
            Request.Builder requestBuilder = original.newBuilder() 
              .addHeader("Authorization", authorizationValue); 

            request = requestBuilder.build(); 
           } 
           return chain.proceed(request); 
          } 
         }) 
       .build(); 
     return okClient; 

    } 

現在在你的改造對象。如果您使用addInterceptor方法添加HttpLoggingInterceptor,它不會被記錄,通過晚於HttpLoggingInterceptor應用於其它攔截器添加的東西添加此頭中的客戶端

Retrofit retrofit = new Retrofit.Builder() 
       .baseUrl(url) 
       .client(getHeader(authorizationValue)) 
       .addConverterFactory(GsonConverterFactory.create()) 
       .build(); 
1

。例如:如果您有兩個攔截器「HttpLoggingInterceptor」和「AuthInterceptor」,並且首先應用HttpLoggingInterceptor,那麼您無法查看由AuthInterceptor設置的http-params或標頭。

OkHttpClient.Builder builder = new OkHttpClient.Builder() 
.addNetworkInterceptor(logging) 
.addInterceptor(new AuthInterceptor()); 

我解決了它,通過使用addNetworkInterceptor方法。