如何在Retrofit请求里添加Cookie

你可以自定义一个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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值