How to retrieve cookies in Retrofit?

后端 未结 4 1512
时光说笑
时光说笑 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 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> 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();
    

提交回复
热议问题