【问题标题】:How to prevent Retrofit from clearing my cookies如何防止 Retrofit 清除我的 cookie
【发布时间】:2014-07-15 18:50:00
【问题描述】:

我从我的后端 API 获得一个 cookie,它允许我验证所有后续用户请求。 我正在使用改造,我无法让它在请求之间保留会话密钥。我想知道如何配置改造,以便它保留会话密钥并将其用于所有未来的请求:

public class ApiClient{

    private static final String API_URL = "http://192.168.1.25:8080";

    private static RestAppApiInterface sRestAppService;

    public static RestAppApiInterface getRestAppApiClient() {
        if (sRestAppService == null) {

            CookieManager cookieManager = new CookieManager();
            cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
            CookieHandler.setDefault(cookieManager);

            RestAdapter restAdapter = new RestAdapter.Builder()
                    .setEndpoint(API_URL)
                    .build();
            sRestAppService = restAdapter.create(RestAppApiInterface.class);
        }
        return sRestAppService;
    }

}

【问题讨论】:

    标签: android json session cookies retrofit


    【解决方案1】:

    如果你使用 Retrofit 2,你可以添加库:

    compile "com.squareup.okhttp3:okhttp-urlconnection:3.2.0"
    

    然后在创建 OkHttp 客户端时使用以下代码管理 cookie:

    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.cookieJar(new JavaNetCookieJar(cookieManager));
    

    【讨论】:

    • 它没有添加到所有请求头中。我该如何解决?
    • 这适用于我使用 RetroFit 和 Magento 1.9.4(扩展自定义登录)
    【解决方案2】:

    您需要设置一个 Cookie 持久客户端。 由于您使用的是 Android 和改造,我建议使用 OKHttp,改造和 Android 线程安全更好地支持,方法如下

    //First create a new okhttpClient (this is okhttpnative)
    OkHttpClient client = new OkHttpClient(); //create OKHTTPClient
    //create a cookieManager so your client can be cookie persistant
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    client.setCookieHandler(cookieManager); //finally set the cookie handler on client
    
    //OkClient is retrofit default client, ofcourse since is based on OkHttClient
    //you can decorate your existing okhttpclient with retrofit's okClient
    OkClient serviceClient = new OkClient(client);
    
    //finally set in your adapter
    RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint("Some eNdpoint")
                .setClient(serviceClient)
                .build();
    

    使用 Okhttp 而不是 defaultHttpClient(by apache) 的重点是 okhttp 对于 android 是线程安全的,并且可以通过改造更好地支持。

    请记住,如果您创建另一个适配器,您将需要设置相同的客户端,也许如果您在客户端实例上实现单例,您将对所有请求使用相同的适配器,并保持在相同的上下文中

    我希望这会有所帮助,最好

    【讨论】:

    • CookiePolicy.ACCEPT_ALL 非常重要,否则无法正常工作,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2011-08-28
    • 2015-10-26
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-27
    相关资源
    最近更新 更多