Android Retrofit2&OkHttp3新增統一的請求頭Header
阿新 • • 發佈:2019-02-04
在使用Retrofit時,有時候需要設定Set-Cookie等請求頭,如果每一個url都需要,那麼直接來個攔截器就好了。
官方說明:
- OkHttp3下OkHttpClient的 List< Interceptor> interceptors()方法,返回的是一個不可編輯的列表,如果對其進行編輯會報出UnSupportedOperationException
- Interceptor的典型使用場景,就是對request和response的Headers進行編輯
如下圖所示:
注意Header頭,不要照抄,要靈活運用。
讓所有網路請求都附上你的 token:
Interceptor mTokenInterceptor = new Interceptor() {
@Override public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
if (Your.sToken == null || alreadyHasAuthorizationHeader(originalRequest)) {
return chain.proceed(originalRequest);
}
Request authorised = originalRequest.newBuilder()
.header("Authorization" , Your.sToken)
.build();
return chain.proceed(authorised);
}
};
為OkHttpClient 新增兩個以上的攔截器,如下程式碼所示:
public class RestDataSource implements Repository {
private final MarvelService mMarvelService;
@Inject
public RestDataSource() {
// Log資訊
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
// 公私密匙
MarvelSigningInterceptor signingInterceptor = new MarvelSigningInterceptor(
BuildConfig.MARVEL_PUBLIC_KEY, BuildConfig.MARVEL_PRIVATE_KEY);
// OkHttp3.0的使用方式
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(signingInterceptor)
.addInterceptor(loggingInterceptor)
.build();
// 選擇人物資訊
Gson customGsonInstance = new GsonBuilder()
.registerTypeAdapter(new TypeToken<List<AvengersCharacter>>() {
}.getType(),
new MarvelResultsDeserializer<AvengersCharacter>())
.create();
// 介面卡
Retrofit marvelApiAdapter = new Retrofit.Builder()
.baseUrl(MarvelService.END_POINT)
.addConverterFactory(GsonConverterFactory.create(customGsonInstance))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(client)
.build();
// 服務
mMarvelService = marvelApiAdapter.create(MarvelService.class);
}
// 返回人物資訊
@Override
public Observable<List<AvengersCharacter>> getCharacters(int currentOffset) {
return mMarvelService.getCharacters(currentOffset);
}
}
下面來個完整的配置:
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
public class RetrofitAPIManager {
public static final String SERVER_URL = "url";
public static ClientAPI provideClientApi() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SERVER_URL)
.client(genericClient())
.build();
return retrofit.create(ClientAPI.class);
}
public static OkHttpClient genericClient() {
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request()
.newBuilder()
.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
.addHeader("Accept-Encoding", "gzip, deflate")
.addHeader("Connection", "keep-alive")
.addHeader("Accept", "*/*")
.addHeader("Cookie", "add cookies here")
.build();
return chain.proceed(request);
}
})
.build();
return httpClient;
}
}