使用CookieHandler与OkHttp和Retrofit 2

4

我在使用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

目前一切都很顺利。我的认证 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个回答

2
我认为您已经正确设置了一切。 在Android中,CookieManager存在一些问题。 我花费了很多时间尝试让它正常工作。结果,我通过拦截器实现了小型自定义cookie管理实现。
您可以阅读更多关于此的信息:
OkHttp中处理cookies
OkHttp 2中处理cookiesAOSP问题75182
此外,您还可以在SO上找到许多相关的帖子。

这很不幸。我将实现一个自定义拦截器,它会自动添加我的 cookies...谢谢。 - pdegand59
@pdegand59或Ilya,你们能否提供一个小例子来展示如何使用自定义拦截器? - Jan
和Jan有同样的问题,所以这里提供链接以防有人搜索:https://github.com/square/okhttp/wiki/Interceptors - AVS

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接