你可以自定義一個RequestIntercaptor:
String cookieKey = ...
String cookieValue = ...
RestAdapter adapter = new RestAdapter.Builder()
.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
// assuming `cookieKey` and `cookieValue` are not null
request.addHeader("Cookie", cookieKey + "=" + cookieValue);
}
})
.setServer("http://...")
.build();
YourService service = adapter.create(YourService.class);
從服務器讀取cookies再交給cookie manager管理:
OkHttpClient client = new OkHttpClient();
CustomCookieManager manager = new CustomCookieManager();
client.setCookieHandler(manager);
RestAdapter adapter = new RestAdapter.Builder()
.setClient(new OkClient(client))
...
.build();
CustomeCookieManager如下:
public class CustomCookieManager extends CookieManager {
private final String SESSION_KEY = "session-key";
/**
* Creates a new instance of this cookie manager accepting all cookies.
*/
public CustomCookieManager() {
super.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
}
@Override
public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException {
super.put(uri, responseHeaders);
if (responseHeaders == null || responseHeaders.get(Constants.SET_COOKIE_KEY) == null) {
return;
}
for (String possibleSessionCookieValues : responseHeaders.get(Constants.SET_COOKIE_KEY)) {
if (possibleSessionCookieValues != null) {
for (String possibleSessionCookie : possibleSessionCookieValues.split(";")) {
if (possibleSessionCookie.startsWith(SESSION_KEY) && possibleSessionCookie.contains("=")) {
String session = possibleSessionCookie.split("=")[1];
return;
}
}
}
}
}
}