Add cookies to retrofit 2 request

First of all: cookie is not the same as a header. Cookie is a special HTTP header named Cookie followed by list of the pairs of keys and values (separated by “;”). Something like:

Cookie: sessionid=sessionid; token=token

Since you cannot set multiple Cookie headers in the same request you are not able to use two @Header annotations for separate values (sessionid and token in your sample). I can think of one very hacky workaround:

@GET("link")
Call<CbGet> getData(@Header("Cookie") String sessionIdAndToken);

You change your method to send sessionId and token in one string. So in this case you should manually generate cookie string beforehand. In your case sessionIdAndToken String object should be equal to “sessionid=here_goes_sessionid; token=here_goes_token

The proper solution is to set cookies by adding OkHttp‘s (that is library Retrofit uses for making underlying http calls) request interceptor. You can see solution or adding custom headers here.

Leave a Comment