
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
}
}
}
}
}
}
Cookie一般用于后台和客户端数据访问的有效保证,由服务端创建,客户端保存,客户端访问时将Cookie保存在请求数据header里面,服务端收到访问请求后,解析出header的库,对本次请求进行有效的验证
移动端网络库一般都是用Retrofit库,Retrofit是对Okhttp的一次很完美的封装,并且可以自定义Okhttp,我们这里使用的方法就是利用拦截器,拦截每一次请求与访问,解析收到的数据,拿到header里面的Cookie,在把Cookie封装到每一帧的请求里面去
//第四步 Retrofit 初始化中加入 client 配置:
跟方法一样的,不同写法。
参考文章:
https://blog.csdn.net/jackzhouyu/article/details/79500148
https://blog.csdn.net/lv_fq/article/details/77132273
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)