How to retrieve cookie from response retrofit, okhttp?
Asked Answered
C

4

22

I am trying to retrieve Cookies values from API response for maintaining the backend session by setting cookie value to new API call in case the APP is closed :

The response to API call from PostMan RestClient: enter image description here

RetrofitClient.java

public static Retrofit getClient() {

    if (checkClient()) {
        return getRetrofit();
    }

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    CookieHandler cookieHandler = new CookieManager();

    okhttp3.OkHttpClient client = new okhttp3.OkHttpClient.Builder().addNetworkInterceptor(interceptor)
            .cookieJar(new JavaNetCookieJar(cookieHandler))
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();

    Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(client)
            .build();
    return retrofit;
}

API Call

private void userLogin(String username, String password) {
    Retrofit retrofit = RetrofitClient.getClient();

    final LoginServices loginServices = retrofit.create(LoginServices.class);
    Call<LoginResponse> call = loginServices.userLogin(username, password);

    call.enqueue(new Callback<LoginResponse>() {
        @Override
        public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
            Log.d("Response code:", "===========" + response.code());

            Log.d("==Cookie==1===", "==="+response.raw().request().headers().get("Cookie"));
            Log.d("==Cookie==2==", "==="+response.headers().get("Cookie"));
            Log.d("==Content-Type====", "==="+response.headers().get("Content-Type"));

        }

        @Override
        public void onFailure(Call<LoginResponse> call, Throwable t) {
            Log.e("TAG", "=======onFailure: " + t.toString());
            t.printStackTrace();
            // Log error here since request failed
        }
    });
}

Logcat:

Response code:: ===========200
==Cookie==1===: ===null
==Cookie==1===: ===null
==Content-Type====: ===application/json

I also tried other various methods they didn't worked for me. Please Help!

Commit answered 4/1, 2018 at 7:20 Comment(4)
response.raw().headers().get("Cookie") try thisAnimalize
already tried, not working @ManthanPatelCommit
@AnuragDhunna, refer to this gist.Collett
@whenthemorningcomes doesn't work :(Commit
S
19
List<String> Cookielist = response.headers().values("Set-Cookie");
String jsessionid = (Cookielist .get(0).split(";"))[0];

This worked for me, not the perfect solution,but it worked

Singlefoot answered 9/1, 2020 at 12:8 Comment(1)
In my case I need to do the following to get it. List<String> Cookielist = response.headers().values("Set-Cookie"); String jsessionid = (Cookielist.get(0).split(";"))[0].split("=")[1];Lepper
M
15

Header name is "Set-Cookie" not "Cookie" and by the way

The approach you are taking It not proper. If you want to save the Cookie, you can create an interceptor and save the Cookie and use later whenever you want to use.

Here what you have to do, First create an interceptor

public class ReceivedCookiesInterceptor implements Interceptor {

PreferencesHelper preferencesHelper;

public ReceivedCookiesInterceptor(Context context) {
    FineractApplication.get(context).getComponent().inject(this);
    preferencesHelper = PreferencesHelper(context)
}

@Override
public Response intercept(Chain chain) throws IOException {
    Response originalResponse = chain.proceed(chain.request());

    if (!originalResponse.headers("Set-Cookie").isEmpty()) {
        HashSet<String> cookies = new HashSet<>();
        for (String header : originalResponse.headers("Set-Cookie")) {
            cookies.add(header);
        }
        // Save the cookies (I saved in SharedPrefrence), you save whereever you want to save
        preferencesHelper.putStringSet(PreferenceKey.PREF_KEY_COOKIES, cookies);
    }
    return originalResponse;
  }
}

Here we are saving all the cookies that you are getting in response.

Now You have cookies it's time to use it.

Wherever you want to use it, just get the cookies that you saved earlier

 HashSet<String> cookies = (HashSet<String>) preferencesHelper.getStringSet(
                        PreferenceKey.PREF_KEY_COOKIES);
        if (cookies != null) {
            for (String cookie: cookies) {  
                // Use this cookie whereever you wanna use.               
                Log.d("Cookie", cookie);                 
            }
        }

Best of luck 👍

Mcwherter answered 19/1, 2018 at 19:13 Comment(1)
Hi i followed this from Gist gist.github.com/nikhiljha/52d45ca69a8415c6990d2a63f61184ff Do I have to call AddCookieInterceptor and ReceiveCookieInterceptor every time I have query to the server? Example: I have login query what Interceptor will I use? Then I have second query like get some data, what Interceptor will i use? Please reply. ThanksPierides
B
3

Try response.headers().get("Set-Cookie"))

Brezhnev answered 4/1, 2018 at 8:38 Comment(1)
this is not entirely correct. to get all cookies using response.headers().values("Set-Cookie")) which returns a List<String> and should have all your cookiesScrub
D
0

I have recently switched to a much simpler way to receive and send cookies with OkHttp and Retrofit, using the CookieJar interface.

First, create a class and implement the CookieJar interface and its functions. In this class, you can receive and send cookies.

import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl

class MyCookieJar : CookieJar {

    val cookieStorage = CookieDataStore()

    override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
        cookieStorage.storeCookies(cookies)
    }

    override fun loadForRequest(url: HttpUrl): List<Cookie> {
        return cookieStorage.getCookies()
    }

} 

Then introduce MyCookieJar to your OkHttpClient:

val okHttpClient = OkHttpClient.Builder()
        .cookieJar(MyCookieJar())
        .build()
Doggy answered 5/9, 2023 at 15:58 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.