gpt4 book ai didi

java - OkHttp CookieJar 向请求添加 cookie 失败

转载 作者:搜寻专家 更新时间:2023-11-01 03:16:58 25 4
gpt4 key购买 nike

我正在尝试使用 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)
}
}
}
}

我的 cookies jar

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"]
}
}

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

最佳答案

我建议使用现有的 cookie jar 而不是创建自己的 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();

还可以设置 OkHttp debug logging with an interceptor 来帮助调试.

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

client.addNetworkInterceptor(logging);

关于java - OkHttp CookieJar 向请求添加 cookie 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46718693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com