Android中OkHttp如何复用PersistentCookieJar存储的Cookie访问页面
Got it, let's break down why your stored cookies from mainPage aren't being automatically sent with the loginPage request, and walk through solutions to get this working smoothly.
What's Likely Going Wrong
You’ve set up PersistentCookieJar correctly and successfully grabbed cookies from mainPage, but they’re not attaching to the loginPage call. The most common culprits here are:
- The cookies you stored have Domain/Path attributes that don’t match the
loginPageURL (OkHttp only sends cookies that fit the request’s domain and path rules) - Rarely, cookie flags like
HttpOnlymight interfere, but that’s unlikely in your scenario since you’re using a standard cookie jar - (You’re already reusing the same
OkHttpClientinstance, so we can rule that out!)
Step-by-Step Solutions
Option 1: Ensure Automatic Cookie Matching (Best Practice)
First, let’s confirm the cookies you’re storing actually apply to loginPage. Add this code to the onResponse of your mainPage call to debug the stored cookies:
@Override public void onResponse(Call call, Response response) throws IOException { if(response.isSuccessful()){ // Check which cookies OkHttp would send to loginPage List<Cookie> applicableCookies = cookieJar.loadForRequest(HttpUrl.parse("http://www.example.com/loginPage")); for(Cookie cookie : applicableCookies){ Log.d("CookieCheck", String.format("Cookie: %s=%s | Domain: %s | Path: %s", cookie.name(), cookie.value(), cookie.domain(), cookie.path())); } // Rest of your existing code... } }
If no cookies show up here, the cookies from mainPage have a domain/path that doesn’t align with loginPage (e.g., maybe the cookie is tied to /main instead of /). Double-check the cookie attributes returned by the website—PersistentCookieJar usually handles this correctly, but it’s worth verifying.
If cookies do show up, confirm that SharedPrefsCookiePersistor is saving them properly (check your app’s SharedPreferences for cookie entries).
Option 2: Manually Attach Cookies to the Request
If automatic matching still isn’t working, we can manually pull the stored cookies and add them to the loginPage request header:
// Fetch cookies that apply to loginPage List<Cookie> loginCookies = cookieJar.loadForRequest(HttpUrl.parse("http://www.example.com/loginPage")); StringBuilder cookieString = new StringBuilder(); // Build the Cookie header value for (int i = 0; i < loginCookies.size(); i++) { Cookie cookie = loginCookies.get(i); if (i > 0) cookieString.append("; "); cookieString.append(cookie.name()).append("=").append(cookie.value()); } // Create the login request with the Cookie header request = new Request.Builder() .url("http://www.example.com/loginPage") .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0") .addHeader("Cookie", cookieString.toString()) // Add the manually built cookie header .build();
This forces the cookies to be included in the request, bypassing any automatic matching issues you might be hitting.
Option 3: Verify Redirect Handling
Occasionally, cookies can get lost during redirects. Make sure your OkHttpClient is configured to follow redirects and carry cookies through them:
client = new OkHttpClient.Builder() .cookieJar(cookieJar) .followRedirects(true) // Explicitly enable redirects (default is true, but good to confirm) .followSslRedirects(true) .build();
This is a secondary check, but it’s worth confirming if you’re still seeing redirects to timeoutPage.
How to Confirm It’s Working
After making changes, add this log to the onResponse of your loginPage call to check if the Cookie header is present:
@Override public void onResponse(Call call, Response response) throws IOException { Log.d("RequestHeaders", "Request Headers: " + call.request().headers().toString()); // Rest of your code... }
If you see the Cookie header in the logs, your request is carrying the cookies correctly, and you should be able to access loginPage without being redirected.
内容的提问来源于stack exchange,提问作者Pera

