android – 使用带有OkHttp和Retrofit 2的CookieHandler

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

我有一个auth请求,如果我的登录是好的,我会回答一个auth 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;路径= /;域= .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永远不会发送回服务器.

上一篇:java – 当互联网断开连接时重新连接OkHttp websocket


下一篇:okhttp支持https双向认证