Using OkHttp by Square https://github.com/square/okhttp, how can I:
Ideally the cookie would be stored, resent and updated automatically with every request.
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.
[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.
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.
Note that starting from Android 4.4, the networking layer (so also the HttpUrlConnection APIs) is implemented through OkHttp.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With