【发布时间】:2015-12-12 21:35:20
【问题描述】:
我在 OkHttp 和 Cookie 管理方面遇到问题。
我正在使用带有 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 是否无法正常工作,还是我试图做一些不可能的事情(除非手动添加标头),或者我只是坏了并且在某个地方失败了?
感谢您的帮助!
【问题讨论】:
标签: android cookies retrofit okhttp