How to retrieve cookies in Retrofit?
Asked Answered
S

4

14

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?

Savannasavannah answered 15/3, 2014 at 15:47 Comment(9)
Have you tried to enable cookies? Just call CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); somewhereArchine
Well if I do that, then does it automatically send the cookie on every request I send out?Savannasavannah
Yes, it will, at least if you are using okhttp as an underlying http-transport implementation. This is the way I handle cookies in my apps.Archine
Where do I call that exactly, on the login page - should that be enough?Savannasavannah
I call it from onCreate method of my custom Application classArchine
but I am saying once, should be enough, and how do you clear it on logout?Savannasavannah
by okhttp as an underlying transport do you just having the lib available? or do I have to add it somehow?Savannasavannah
@Savannasavannah It's enough to have OkHttp lib in our classpath. Retrofit can detect this and plug OkHttp in.Necropsy
Related: https://mcmap.net/q/153474/-retrofit-amp-auth-cookieBrainpan
C
10

I had similar situation in my app. This solution works for me to retrieve cookies using Retrofit. MyCookieManager.java

import java.io.IOException;
import java.net.CookieManager;
import java.net.URI;
import java.util.List;
import java.util.Map;

class MyCookieManager extends CookieManager {

    @Override
    public void put(URI uri, Map<String, List<String>> stringListMap) throws IOException {
        super.put(uri, stringListMap);
        if (stringListMap != null && stringListMap.get("Set-Cookie") != null)
            for (String string : stringListMap.get("Set-Cookie")) {
                if (string.contains("userid")) {
                    //save your cookie here
                }
            }
    }
}

Here is how to set your cookie for future requests using RequestInterceptor:

 MyCookieManager myCookieManager = new MyCookieManager();
            CookieHandler.setDefault(myCookieManager);
 private static final RestAdapter REST_ADAPTER = new RestAdapter.Builder()
            .setEndpoint(API_URL)
            .setLogLevel(RestAdapter.LogLevel.FULL)
                    .setRequestInterceptor(new RequestInterceptor() {
                        @Override
                        public void intercept(RequestFacade requestFacade) {
                            String userId = ;//get your saved userid here
                            if (userId != null)
                                requestFacade.addHeader("Cookie", userId);
                        }
                    })
            .build();
Complexity answered 15/9, 2014 at 15:38 Comment(1)
Definitely one of the better answers out there. Although, I personally wouldn't do the CookieHandler.setDefault, but that's my choice (I hate affecting system-wide) - I use okHttpClient.setCookieHandler(cookieManager) - other alternatives are to mess with the InterceptorsGumbo
F
1

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

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

Frig answered 4/6, 2016 at 17:44 Comment(1)
How to remove this cookie when logout ??Wooton
C
0

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
    }

}
Chili answered 3/8, 2018 at 9:45 Comment(0)
B
0

@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!

Breadstuff answered 15/10, 2018 at 9:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.