android - management - retrofit set cookie header




How to retrieve cookies in Retrofit? (3)

@Rafolos Your answer saved me, it's perfect and clean. You just have to make sure to use the same interceptor object for all your following requests, otherwise if you instantiate a new CookiesInterceptor for each call, the cookie will be null.

I have a RetrofitProvider object with this property:

private val cookiesInterceptor: CookiesInterceptor by lazy {
    CookiesInterceptor()
}

Then I use it like this:

private fun provideOkHttpClient(): OkHttpClient {
    val httpClient = OkHttpClient.Builder()

    httpClient.addInterceptor(this.cookiesInterceptor)
    // add some other interceptors

    return httpClient.build()
}

and it works like a charm. Thank you!

I read about request interceptors and what not but no clue how to really use them to obtain cookies... I am sending the cookie like so from nodejs...

res.cookie('userid', user._id, { maxAge: 86400000, signed: true, path: '/' });

And in my android client - I have this set up so far for my RestApiManager

public class RestApiManager {
  private static final String API_URL = "ip: port";

    private static final RestAdapter REST_ADAPTER = new RestAdapter.Builder()
            .setEndpoint(API_URL)
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .build();

    //Call interface
    public interface AsynchronousApi {
  //Login User
        @FormUrlEncoded
        @POST("/login")
        public void loginUser(
                @Field("loginName") String loginName,
                @Field("password") String password,
                Callback<UserResponse> callback);
//Profile Picture
        @Multipart
        @POST("/profilePicture")
        public void uploadProfilePicture(
                @Part("photo") TypedFile photo,
                @Part("userId") String userId,
                Callback<UserResponse> callback); //success thumbnail to picasso

    }
    //create adapter
    private static final AsynchronousApi ASYNCHRONOUS_API = REST_ADAPTER.create(AsynchronousApi.class);

    //call service to initiate
    public static AsynchronousApi getAsyncApi() {
        return ASYNCHRONOUS_API;
    }
}

Separate cookie class:

    public class ApiCookie implements RequestInterceptor{
    // cookie use
    private String sessionId;

    public ApiCookie() {

    }

    //COOKIE BELOW
    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }

    public void clearSessionId() {
        sessionId = null;
    }


    @Override
    public void intercept(RequestFacade requestFacade) {
        setSessionId();
    }
}

trying to figure out how to obtain the cookie and be able to send it with future requests, so I do not need to include a userId field?


I created interceptor in Kotlin to retreive cookie (filter out the cookie for only http) and send in header in every request until user logout (and use clearCookie() method)

class CookiesInterceptor: Interceptor {

    companion object {
        const val COOKIE_KEY = "Cookie"
        const val SET_COOKIE_KEY = "Set-Cookie"
    }

    fun clearCookie() {
        cookie = null
    }

    private var cookie: String? = null

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val requestBuilder = request.newBuilder()
        cookie?.let { requestBuilder.addHeader(COOKIE_KEY, it) }

        val response = chain.proceed(requestBuilder.build())
        response.headers()
                .toMultimap()[SET_COOKIE_KEY]
                ?.filter { !it.contains("HttpOnly") }
                ?.getOrNull(0)
                ?.also {
                    cookie = it
                }

        return response
    }

}

Simple solution using lib. compile 'com.squareup.okhttp3:okhttp-urlconnection:3.2.0'.

JavaNetCookieJar jncj = new JavaNetCookieJar(CookieHandler.getDefault()); OkHttpClient.Builder().cookieJar(jncj).build();





retrofit