Is there a way to set a custom cookie on retrofit requests?
Either by using the RequestInterceptor
or any other means?
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);
}
}