如何在Retrofit请求里添加Cookie
来源:互联网 发布:淘宝电子发票怎么下载 编辑:程序博客网 时间:2024/06/06 00:29
你可以自定义一个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; } } } } }}
0 1
- 如何在Retrofit请求里添加Cookie
- retrofit请求持久化Cookie
- 如何在Android应用里对HTTP请求头部添加适当的User-Agent字段
- 如何在Android应用里对HTTP请求头部添加适当的User-Agent字段
- java 客户端请求服务器 ,在头部添加cookie
- Retrofit使用OkHttp保存和添加cookie
- 如何在TLISTVIEW里添加背景色
- 如何在开始菜单里添加快捷方式???
- 在WORD文档里如何添加编号
- 如何在LuCI里添加print?
- 如何在UITableView里动态添加 cell
- 如何在Word工具栏里添加MathType
- 如何批量在mysql里添加数据
- 修改他人程序,在请求里添加自己的用户
- 如何在命令行里添加 第三方包到 classpath里?
- Retrofit 请求体header的添加
- 如何在发起HTTP请求时附带Cookie
- Angularjs之如何在跨域请求中传输Cookie
- java urlrewrite实现伪静态化
- iOS7 中 boundingRectWithSize:options:attributes:context:计算文本尺寸的使用
- JavaScript基础——引用类型(四)基本包装类型(Boolean、Number、String)、单体内置对象(Global、Math)
- Android轮播图原理
- HashMap工作原理
- 如何在Retrofit请求里添加Cookie
- 应用包已上传,但itunesconnect后台构建版本处在正在审核中
- secureCRT彩色字体设置
- 连续最大子序列和与最小子序列和
- Middle-题目56:109. Convert Sorted List to Binary Search Tree
- XenServer关键的配置文件
- Jquery 常用函数学习记录
- Runtime的简单使用
- android多分辨率适配