Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement cookie handling on Android using OkHttp?

Using OkHttp by Square https://github.com/square/okhttp, how can I:

  1. Retrieve a cookie returned from the server
  2. Store the cookie for upcoming requests
  3. Use the stored cookie in subsequent requests
  4. Update the cookie returned by the subsequent request

Ideally the cookie would be stored, resent and updated automatically with every request.

like image 364
Daniel Avatar asked Jun 17 '14 12:06

Daniel


People also ask

How do I use OkHttp on Android?

OkHttp Query Parameters ExampleBuilder urlBuilder = HttpUrl. parse("https://httpbin.org/get).newBuilder(); urlBuilder. addQueryParameter("website", "www.journaldev.com"); urlBuilder. addQueryParameter("tutorials", "android"); String url = urlBuilder.

What is CookieJar Android?

[jvm]\ interface CookieJar. Provides policy and persistence for HTTP cookies. As policy, implementations of this interface are responsible for selecting which cookies to accept and which to reject.

What is the use of OkHttp?

OkHttp is an HTTP client from Square for Java and Android applications. It's designed to load resources faster and save bandwidth. OkHttp is widely used in open-source projects and is the backbone of libraries like Retrofit, Picasso, and many others.

Does HttpUrlConnection use OkHttp?

Note that starting from Android 4.4, the networking layer (so also the HttpUrlConnection APIs) is implemented through OkHttp.


1 Answers

For OkHttp3, a simple accept-all, non-persistent CookieJar implementation can be as follows:

OkHttpClient client = new OkHttpClient.Builder()     .cookieJar(new CookieJar() {         private final HashMap<HttpUrl, List<Cookie>> cookieStore = new HashMap<>();          @Override         public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {             cookieStore.put(url, cookies);         }          @Override         public List<Cookie> loadForRequest(HttpUrl url) {             List<Cookie> cookies = cookieStore.get(url);             return cookies != null ? cookies : new ArrayList<Cookie>();         }     })     .build(); 

Or if you prefer to use java.net.CookieManager, include okhttp-urlconnection in your project, which contains JavaNetCookieJar, a wrapper class that delegates to java.net.CookieHandler:

dependencies {     compile "com.squareup.okhttp3:okhttp:3.0.0"     compile "com.squareup.okhttp3:okhttp-urlconnection:3.0.0" } 

CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); OkHttpClient client = new OkHttpClient.Builder()     .cookieJar(new JavaNetCookieJar(cookieManager))     .build(); 
like image 126
hidro Avatar answered Sep 23 '22 07:09

hidro