如何在Retrofit请求里添加Cookie

 我来答
看ti的程序员
2016-09-08 · TA获得超过456个赞
知道小有建树答主
回答量:444
采纳率:50%
帮助的人:207万
展开全部
你可以自定义一个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 {

// The cookie key we're interested in.
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) {
// No cookies in this response, simply return from this method.
return;
}

// Yes, we've found cookies, inspect them for the key we're looking for.
for (String possibleSessionCookieValues : responseHeaders.get(Constants.SET_COOKIE_KEY)) {

if (possibleSessionCookieValues != null) {

for (String possibleSessionCookie : possibleSessionCookieValues.split(";")) {

if (possibleSessionCookie.startsWith(SESSION_KEY) && possibleSessionCookie.contains("=")) {

// We can safely get the index 1 of the array: we know it contains
// a '=' meaning it has at least 2 values after splitting.
String session = possibleSessionCookie.split("=")[1];

// store `session` somewhere

return;
}
}
}
}
}
}
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式