How to retrieve cookies in Retrofit?

后端 未结 4 1507
时光说笑
时光说笑 2020-12-03 21:15

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.coo         


        
相关标签:
4条回答
  • 2020-12-03 21:57

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

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

    0 讨论(0)
  • 2020-12-03 21:59

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

    0 讨论(0)
  • 2020-12-03 22:03

    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();
    
    0 讨论(0)
  • 2020-12-03 22:03

    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
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题