Using CookieHandler with OkHttp and Retrofit 2

I'm having problems managing OkHttp and Cookies.

I am creating a RetoFit client with a custom OkHttpClient with CookieManager.

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();

I have an auth request that responds to my cookie if my username is good:

interface AuthService {
    @POST
    @FormUrlEncoded
    Call<String> auth(@Url String url,
                      @Field("login") String login,
                      @Field("password") String password);
}

Using it as follows:

mAuthService = retrofit.create(AuthService.class);
mAuthService.auth("https://auth.mysite.com/some/path", "mylogin", "mypassword")
            .enqueue(new AuthCallback());

In the response headers of this request, I have one such:

Set-Cookie: auth=someauthkey468TYUIYTYUY; path=/; domain=.mysite.com

After the request, if I look at the cookie handler, there is one entry on the cookie storage map:

key = http://auth.mysite.com 
value = a list of cookie with only auth=someauthkey468TYUIYTYUY

At this point, everything is working well. My cookie is completely stored in the cookie handler.

But now I want to fulfill a request to load some data using another service:

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 OkHttp, - ( ), - ?

!

+4
1

, . CookieManager Android. , . cookie .

:

cookie OkHttp

cookie OkHttp 2

AOSP 75182

SO

+1

Source: https://habr.com/ru/post/1607625/


All Articles