我在管理 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());
在这个请求的响应头中,我有这样一个:
设置 Cookie:auth=someauthkey468TYUIYTYUY;路径=/;域名=.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 管理的小型自定义实现。
您可以阅读更多相关信息:
你也可以在 SO 上找到很多相关的帖子
关于android - 将 CookieHandler 与 OkHttp 和 Retrofit 2 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32606218/