OkHttp CookieJar 无法向请求添加 cookie

Ant*_*ert 6 java cookies kotlin okhttp

我正在尝试使用 CookieJar 将保存的身份验证 cookie 添加到进一步的请求中。虽然获取正确的身份验证 cookie 并将其保存到 jar 中效果很好,但在检查 时response.request().headers(),cookie 无处可寻。

我发现这特别奇怪,因为我通过调试发现loadForRequest()请求调用并返回正确的 cookie。在 Postman 中使用完全相同的 cookie 来伪造请求时,它会返回所需的结果(没有登录表单的页面)。

有人可以尝试解释我缺少什么吗?

使用 jar 的类

class HTMLRoutes {
    var scheme = "https"
    var host = "www.mangaupdates.com"
    val cookieJar = MULoginCookieJar()
    var client = OkHttpClient.Builder()
            .cookieJar(cookieJar)
            .build()
/*Other code*/

private fun getHTMLFromUrl(url: HttpUrl): String {
        var request = Request.Builder()
                .url(url)
                .build()
        client.newCall(request).execute().use { response ->
        //Right before returning response the loadForRequest() method gets called in the MUCookieJar class
            if (response.isSuccessful) {
            //response.request.headers = ""
                if (response.body() != null) {
                    return response.body()!!.string()
                } else {
                    throw IOException("Response body is empty")
                }
            } else {
                throw IOException("Unexpected code" + response)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的饼干罐

class MULoginCookieJar : CookieJar {
    private var secureSessionCookie: Cookie? = null

    override fun saveFromResponse(url: HttpUrl?, cookies: MutableList<Cookie>?) {
        if (url != null && cookies != null) {
            if (url.pathSegments().size > 0 && url.pathSegments()[0] == "login.html") {
                for (cookie in cookies) {
                    if(cookie.name() == "secure_session") {
                        secureSessionCookie = cookie
                    }
                }
            }
        }
    }

    override fun loadForRequest(url: HttpUrl?): List<Cookie>? { // url = https://www.mangaupdates.com/series.html?id=14829
        if(url != null && url.pathSegments().size > 0 && url.pathSegments()[0] == "login.html") {
            return emptyList()
        }

        val cookies: List<Cookie> = if(secureSessionCookie==null) emptyList() else listOf(secureSessionCookie!!)
        return cookies // = ["secure_session=601bbc74; expires=Sun, 07 Oct 2018 20:45:24 GMT; domain=www.mangaupdates.com; path=/; secure; httponly"]
    }
}
Run Code Online (Sandbox Code Playgroud)

非常感谢帮助。我潜伏了很长时间,但这是我第一次被一个问题难住。

Bil*_*eil 6

我建议使用现有的 cookie jar 而不是创建自己的。围绕 cookie 的规则可能会变得有点复杂。

import okhttp3.JavaNetCookieJar;

CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
JavaNetCookieJar cookieJar = new JavaNetCookieJar(cookieManager);

OkHttpClient client = new OkHttpClient.Builder().cookieJar(cookieJar).build();
Run Code Online (Sandbox Code Playgroud)

同样为了帮助调试,您可以使用拦截器设置OkHttp 调试日志记录

Logger logger = LoggerFactory.getLogger(HttpUtil.class);
HttpLoggingInterceptor logging =
    new HttpLoggingInterceptor((msg) -> {
        logger.debug(msg);
    });
logging.setLevel(Level.BODY);

client.addNetworkInterceptor(logging);
Run Code Online (Sandbox Code Playgroud)