2015-09-16 61 views
4

我遇到了OkHttp和Cookies管理的麻烦。使用CookieHandler与OkHttp和改造2

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

我想你设置都正确。 有一些问题与CookieManager在Android系统。 我花了很多时间试图使它的作品。至于结果,我实现了通过拦截器的cookies同治的小自定义实现。

你可以阅读更多关于它:

Do cookies in OkHttp

Do cookies in OkHttp 2

AOSP issue 75182

你也能找到SO

+0

很多相关的帖子嗯,这是不幸的。我将实现一个自定义拦截器,它会自动添加我的cookie ...谢谢 – pdegand59

+0

@ pdegand59或Ilya,你可以发表一个如何做这个自定义拦截器的小例子吗? – Jan

+0

与Jan有同样的问题,所以这里是链接是有人来搜索的情况:https://github.com/square/okhttp/wiki/Interceptors – AVS