1. 程式人生 > >Android Retrofit2&OkHttp3新增統一的請求頭Header

Android Retrofit2&OkHttp3新增統一的請求頭Header


在使用Retrofit時,有時候需要設定Set-Cookie等請求頭,如果每一個url都需要,那麼直接來個攔截器就好了.

讓所有網路請求都附上你的 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); } };

完整用法:

public class HttpUtils {

    private String token = null;
    private static 
HttpUtils self = new HttpUtils(); private HttpUtils() { } public static HttpUtils getInstance() { return self; } public <T> T createRequest(Class<? extends T> t) { Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd hh:mm:ss") .create();
Retrofit retrofit = new Retrofit.Builder() .baseUrl(BaseConstant.BASE_REQUEST_URL) .client(genericClient()) .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); return retrofit.create(t); } //統一攔截器 private OkHttpClient genericClient() { UserModel user = (UserModel) ACache.getAsObject("user"); if (user == null) { token = ""; } else { token = user.getToken(); } return new OkHttpClient.Builder() .addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request() .newBuilder() .addHeader("Authorization", token) .build(); return chain.proceed(request); } }) .build(); } public MultipartBody.Part createMultipartBody(String key, String fileName, File source) { RequestBody file = RequestBody.create(MediaType.parse(BaseConstant.APPLICATION_OCTET_STREAM), source); return MultipartBody.Part.createFormData(key, fileName, file); } }