Is there a way to set a custom cookie on retrofit requests?
Either by using the RequestInterceptor
or any other means?
I've only just started with RetroFit, but the way it handles cookies does not seem to be on par with the rest of the library. I wound up doing something like this:
// Set up system-wide CookieHandler to capture all cookies sent from server.
final CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);
// Set up interceptor to include cookie value in the header.
RequestInterceptor interceptor = new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
for (HttpCookie cookie : cookieManager.getCookieStore().getCookies()) {
// Set up expiration in format desired by cookies
// (arbitrarily one hour from now).
Date expiration = new Date(System.currentTimeMillis() + 60 * 60 * 1000);
String expires = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz")
.format(expiration);
String cookieValue = cookie.getName() + "=" + cookie.getValue() + "; " +
"path=" + cookie.getPath() + "; " +
"domain=" + cookie.getDomain() + ";" +
"expires=" + expires;
request.addHeader("Cookie", cookieValue);
}
}
};
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://api.github.com")
.setRequestInterceptor(interceptor) // Set the interceptor
.build();
GitHubService service = restAdapter.create(GitHubService.class);