I need to know how to add an authorization cookie header in retrofit. I have seen advice like using request intercepter etc. Below is what I am trying, but is this correct? First of all I already needed a RequestAdatper to get the session id the first time around. This can only be set by the builder of the request adapter. But I needed to make a request just to get the session id in the first place. Do I need two rest adapters one to get the sessionId and another one after I have obtained it. What I really need is a method on adapter to set the cookie after I get it but it does not appear to be such a method. This is getting awkward. How do I set authorization cookie in retrofit? I don't see this in FAQ or tutorials.
RequestInterceptor requestInterceptor = new RequestInterceptor()
{
@Override
public void intercept(RequestFacade request) {
request.addHeader("Set-Cookie", "sessionId="+sessionIdentifier);
}
};
RestAdapter.Builder().setServer(serverURL)..setRequestIntercepter(requestIntercepter).build();
// but I don't have sessionId when this is first issued ???
According to @sbtgE's answer, but with some corrections.
CookieHandler.getDefault()
may be null, so I use CookieManager.app's build.gradle:
Setting up Retrofit:
Keep a reference to the interceptor and treat it as a singleton like you would be
RestAdapter
itself.Now, simply call
setSessionId
after your authentication call. All subsequent requests will include the header.You can get the cookies like this
Use this to set the CookieHandler
and then use it like this in your request Interceptor
Step 1. Parse Response headers. Call this method inside your Callback in overriden
success
method.Step 2. Write some static class or singleton to keep cookies and your RequestInterceptor instance. Inside RequestInterceptor override intercept method to add your cookies to Header.
Simple solution using lib. compile
com.squareup.okhttp3:okhttp-urlconnection:3.2.0
.JavaNetCookieJar jncj = new JavaNetCookieJar(CookieHandler.getDefault()); OkHttpClient.Builder().cookieJar(jncj).build();