【问题标题】:Using CookieHandler with OkHttp and Retrofit 2将 CookieHandler 与 OkHttp 和 Retrofit 2 一起使用
【发布时间】: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


    【解决方案1】:

    我认为您正确设置了所有内容。 Android 中的 CookieManager 存在一些问题。 我花了很多时间试图让它发挥作用。结果,我通过拦截器实现了 cookie 管理的小型自定义实现。

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

    Do cookies in OkHttp

    Do cookies in OkHttp 2

    AOSP issue 75182

    你也可以在 SO 上找到很多相关的帖子

    【讨论】:

    • 这很不幸。我将实现一个自定义拦截器,它会自动添加我的 cookie……谢谢
    • @pdegand59 或 Ilya,你能发布一个如何实现自定义拦截器的小例子吗?
    • 和 Jan 有同样的问题,所以这里是有人来搜索的链接:github.com/square/okhttp/wiki/Interceptors
    猜你喜欢
    • 2023-03-16
    • 1970-01-01
    • 2016-11-27
    • 2023-03-20
    • 2014-04-20
    • 1970-01-01
    • 2017-05-25
    • 2016-04-24
    • 2016-09-23
    相关资源
    最近更新 更多