在翻新中设置自定义Cookie [英] Set custom cookie in Retrofit

查看:69
本文介绍了在翻新中设置自定义Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在改装请求上设置自定义Cookie?

Is there a way to set a custom cookie on retrofit requests?

是使用 RequestInterceptor 还是其他任何方式?

Either by using the RequestInterceptor or any other means?

推荐答案

通过 retrofit.RequestInterceptor :

@Override
public void intercept(RequestFacade request) {    
     request.addHeader("Cookie", "cookiename=cookievalue");
}

您可以如下设置自定义的 RequestInterceptor :

You can set a custom RequestInterceptor as follows:

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);

要读取服务器设置的任何cookie,请附加一个自定义cookie管理器,如下所示:

And to read any cookies set by the server, attach a custom cookie manager like this:

OkHttpClient client = new OkHttpClient();
CustomCookieManager manager = new CustomCookieManager();
client.setCookieHandler(manager);

RestAdapter adapter = new RestAdapter.Builder()
    .setClient(new OkClient(client))
    ...
    .build();

其中 CustomCookieManager 可能看起来像这样:

where CustomCookieManager could look like this:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆