SetCookie from the client side with OkHttp3

Task

When communicating with Android on the server (HTTP base), there is a request to set the cookie on the Android client side due to the server's convenience, and from the Android side with OkHttp3 (http://square.github.io/okhttp/) I thought about how to setCookie.

Library used ok http / 3.6.0

Preface

When I searched for a solution already, there were some similar topics, but it was slightly different from what I was looking for (or could not be solved), so I decided to make it myself.

--An example of forcing a set cookie is a method of overwriting with intercept. http://stackoverflow.com/questions/35743291/add-cookie-to-client-request-okhttp/43014982#43014982

--OkHttp3 cookie handling and persistence https://github.com/franmontiel/PersistentCookieJar

solution

I created a helper class called ** OkHttp3CookieHelper **. The following will force the client to set its own cookie. Of course, other cookies issued by the server are also handled. If you need a persistence mechanism, add it. There seems to be no problem with on-memory for the time being.

The code below is platform independent and will work on both Pure Java and Android.

Sample code


		String url = "https://example.com/webapi";

		OkHttp3CookieHelper cookieHelper = new OkHttp3CookieHelper();
		cookieHelper.setCookie(url, "cookie_name", "cookie_value");
		
		OkHttpClient client = new OkHttpClient.Builder()
				.cookieJar(cookieHelper.cookieJar())
				.build();

		Request request = new Request.Builder()
				.url(url)
				.build();

Helper class source code

OkHttp3CookieHelper.java


public class OkHttp3CookieHelper {

	private final Map<String, List<Cookie>> mServerCookieStore = new ConcurrentHashMap<String, List<Cookie>>();

	private Map<String, List<Cookie>> mClientCookieStore = new ConcurrentHashMap<String, List<Cookie>>();

	private final CookieJar mCookieJar = new CookieJar() {
		@Override
		public List<Cookie> loadForRequest(HttpUrl url) {

			List<Cookie> serverCookieList = mServerCookieStore.get(url.host());

			if (serverCookieList == null) {
				serverCookieList = new ArrayList<Cookie>();
			}

			final List<Cookie> clientCookieStore = mClientCookieStore.get(url.host());

			if (clientCookieStore != null) {
				serverCookieList.addAll(clientCookieStore);
			}

			return serverCookieList != null ? serverCookieList : new ArrayList<Cookie>();
		}

		@Override
		public void saveFromResponse(HttpUrl url, List<Cookie> unmodifiableCookieList) {
			mServerCookieStore.put(url.host(), new ArrayList<Cookie>(unmodifiableCookieList));
		}

	};

	public void setCookie(String url, Cookie cookie) {

		final String host = HttpUrl.parse(url).host();

		List<Cookie> cookieListForUrl = mClientCookieStore.get(host);
		if (cookieListForUrl == null) {
			cookieListForUrl = new ArrayList<Cookie>();
			mClientCookieStore.put(host, cookieListForUrl);
		}
		putCookie(cookieListForUrl, cookie);

	}

	public void setCookie(String url, String key, String value) {
		final HttpUrl httpUrl = HttpUrl.parse(url);
		setCookie(url, Cookie.parse(httpUrl, key + "=" + value));
	}

	public void setCookie(HttpUrl httpUrl, String key, String value) {
		setCookie(httpUrl.host(), Cookie.parse(httpUrl, key + "=" + value));
	}

	public CookieJar cookieJar() {
		return mCookieJar;
	}

	private void putCookie(List<Cookie> storedCookieList, Cookie newCookie) {

		Cookie oldCookie = null;
		for (Cookie storedCookie : storedCookieList) {

			// create key for comparison
			final String oldCookieKey = storedCookie.name() + storedCookie.path();
			final String newCookieKey = newCookie.name() + newCookie.path();

			if (oldCookieKey.equals(newCookieKey)) {
				oldCookie = storedCookie;
				break;
			}
		}
		if (oldCookie != null) {
			storedCookieList.remove(oldCookie);
		}
		storedCookieList.add(newCookie);
	}

}

Publication destination

The code is published below

github https://github.com/riversun/okhttp3-cookie-helper

gradle compile 'org.riversun:okhttp3-cookie-helper:1.0.1'

maven

<dependency>
<groupId>org.riversun</groupId>
<artifactId>okhttp3-cookie-helper</artifactId>
<version>1.0.1</version>
</dependency>

Recommended Posts

SetCookie from the client side with OkHttp3
How to disable Set-Cookie from API on the front side
API integration from Java with Jersey Client
Insert the selenium cookie into the okHttp3 client
[Java] Set the time from the browser with jsoup
Spring with Kotorin --3. Omitting curly braces from the function
Vibrate the wristband device with Bluetooth from the Android app
Find the address class and address type from the IP address with Java
[MT] Specify the article category from Android with Data API
Set the date and time from the character string with POI
[MT] Specify the article category from Android with Data API
I tried upgrading from CentOS 6.5 to CentOS 7 with the upgrade tool