2015-09-16 57 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