将 CookieHandler 与 OkHttp 和 Retrofit 2 一起使用

Using CookieHandler with OkHttp and Retrofit 2

我在管理 OkHttp 和 Cookies 时遇到问题。

我正在使用带有 CookieManager 的自定义 OkHttpClient 创建 Retrofit 客户端。

final OkHttpClient okHttpClient = new OkHttpClient();
mCookieHandler = new CookieManager();
okHttpClient.setCookieHandler(mCookieHandler);
final Retrofit retrofit = new Retrofit.Builder()
       .baseUrl("http://api.mysite.com/")
       .client(okHttpClient)
       .addConverter(String.class, new StringConverter())
       .build();

然后我收到一个身份验证请求,如果我的登录正常,它会回答我一个身份验证 cookie:

interface AuthService {
    @POST
    @FormUrlEncoded
    Call<String> auth(@Url String url,
                      @Field("login") String login,
                      @Field("password") String password);
}

像这样使用它:

mAuthService = retrofit.create(AuthService.class);
mAuthService.auth("https://auth.mysite.com/some/path", "mylogin", "mypassword")
            .enqueue(new AuthCallback());

在这个请求的响应 header 中,我有这样一个:

Set-Cookie: auth=someauthkey468TYUIYTYUY; path=/; domain=.mysite.com

请求后,如果我查看 cookie 处理程序内部,cookie 存储映射中有一个条目:

key = http://auth.mysite.com 
value = a list of cookie with only auth=someauthkey468TYUIYTYUY

此时一切正常。我的身份验证 cookie 完美地存储在 cookie 处理程序中。

但是现在,我想执行一个请求,用另一个服务下载一些数据:

interface UserService {
    @GET("user") // remember that the base url of retrofit is http://api.mysite.com/
    Call<String> getMyCurrentInfo();
}

retrofit.create(UserService.class).getMyCurrentInfo().execute();

在这里,我希望 OkHttp 将存储在 cookie 处理程序中的先前接收到的 cookie 添加到此请求中,但 OkHttp 没有添加 header! cookie 永远不会发送回服务器。 :(

Cookie 处理程序和 OkHttp 是否存在某些问题,或者我是否在尝试做一些不可能的事情(除非手动添加 header),或者我只是不好并且在某处失败了?

感谢您的帮助!

我认为您设置正确。 Android 中的 CookieManager 存在一些问题。 我花了很多时间试图让它发挥作用。结果,我通过拦截器实现了 cookie 管理的小型自定义实现。

您可以阅读更多相关信息:

Do cookies in OkHttp

Do cookies in OkHttp 2

AOSP issue 75182

您还可以在 SO

上找到许多相关的 post