将CookieHandler与OkHttp和Retrofit 2一起使用

时间:2015-09-16 10:36:00

标签: android cookies retrofit okhttp

我遇到了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());

在此请求的响应标头中,我有一个这样的:

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

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

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

此时每件事情都很好。我的auth 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没有添加任何标头! cookie永远不会发送回服务器。 :(

有没有使用Cookie处理程序和OkHttp的东西,或者我正在尝试做一些不可能的事情(除非手动添加标题)或者我只是在某个地方做坏事并失败了?

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

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

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

Do cookies in OkHttp

Do cookies in OkHttp 2

AOSP issue 75182

你也可以在SO

找到很多相关的帖子