Set custom cookie in Retrofit

后端 未结 4 1298
南旧
南旧 2021-01-31 05:23

Is there a way to set a custom cookie on retrofit requests?

Either by using the RequestInterceptor or any other means?

4条回答
  •  一生所求
    2021-01-31 06:14

    This is how it's done for retrofit2

    Gradle:

    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    

    The code:

    static final class CookieInterceptor implements Interceptor {
                private volatile String cookie;
    
                public void setSessionCookie(String cookie) {
                    this.cookie = cookie;
                }
    
                @Override
                public okhttp3.Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();
                    if (this.cookie != null) {
                        request = request.newBuilder()
                                .header("Cookie", this.cookie)
                                .build();
                    }
                    return chain.proceed(request);
                }
    }
    
    
    class Creator {
    
        public static MyApi newApi() {
            Gson gson = new GsonBuilder()
                    .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
                    .create();
    
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(new CookieInterceptor())
                    .build();
    
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(MyApi.URL)
                    .callFactory(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
            return retrofit.create(MyApi.class);
        }
    }
    

提交回复
热议问题