Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using retrofit with Cookie persistence

I guys, I'm using retrofit and I wonder how to transparently handle the session cookie. For that I extend the given ApacheClient and use a CookieStore in the custom call to ApacheClient.execute(HttpClient, HttpUriRequest) :

Client client = new ApacheClient() {
    final CookieStore cookieStore = new BasicCookieStore();
    @Override
    protected HttpResponse execute(HttpClient client, HttpUriRequest request) throws IOException {
        // BasicHttpContext is not thread safe 
        // CookieStore is thread safe
        BasicHttpContext httpContext = new BasicHttpContext();
        httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        return client.execute(request, httpContext);
    }
};

RestAdapter restAdapter = new RestAdapter.Builder()
    .setServer(API_URL)
    .setClient(client)
    .build();

Is there a better way to do this with the build-in retrofit API (with no HttpClient extension) ?

like image 981
avianey Avatar asked Sep 19 '13 12:09

avianey


1 Answers

Starting from API 9 you have java.net.CookieManager and can set system-wide cookie handler like this:

CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);

Yes, Apache Http client uses its own cookie-handling mechanism. But it should not be the problem because starting from API 9 HttpURLConnection is recommended HTTP client. If you use Retrofit from Square you may also like their OkHttp lib - custom URLConnection implementation with lots of useful capabilities.

like image 127
colriot Avatar answered Nov 15 '22 13:11

colriot