You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ktor HttpResponse setCookies()仅返回单个Cookie,如何获取全部Cookie?

问题描述

我正在尝试通过API完成身份验证,需要获取响应中的Set-Cookie内容。在浏览器开发者工具里能看到多个所需的Cookie,但用以下代码请求后,仅能拿到和datadome相关的Cookie,无法获取全部需要的Cookie。

我的代码

val client = HttpClient()

class LoginConnection {
    suspend fun login(
        email: String,
        password: String,
        onCookieReceived: suspend  (List<Cookie>?) -> Unit
    ){
        val res = client.submitForm(
            url =  "https://users.premierleague.com/accounts/login/",
            formParameters = parameters {
                append("login", email)
                append("password", password)
                append("app", "plfpl-web")
                append("redirect-uri", "https://fantasy.premierleague.com/")
            }
        ) {
            headers {
                append(HttpHeaders.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36")
                append(HttpHeaders.AcceptLanguage, "en")
            }
            method = HttpMethod.Post
        }
        val cookie = res.setCookie()
        println(cookie)
        try {
            onCookieReceived(
                cookie
            )
        }catch (e: Exception){
            onCookieReceived(null)
        }
    }
}
解决办法
  • 禁用自动重定向
    默认HttpClient会自动跟随重定向,导致登录接口直接返回的Cookie被遗漏。修改客户端配置禁用重定向:

    val client = HttpClient {
        followRedirects = false
    }
    

    这样就能获取到登录接口响应的所有Cookie,之后可自行处理重定向逻辑。

  • 手动解析所有Set-Cookie头
    res.setCookie()可能会过滤掉Domain/Path不匹配当前请求的Cookie,直接从响应头中解析所有Set-Cookie字段:

    val allCookies = res.headers.getAll(HttpHeaders.SetCookie)?.mapNotNull { cookieStr ->
        Cookie.parse(cookieStr)
    }
    
  • 补充浏览器标准请求头
    浏览器请求时会携带更多头信息,补充这些字段可能让服务器返回完整Cookie:

    headers {
        append(HttpHeaders.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36")
        append(HttpHeaders.AcceptLanguage, "en")
        append(HttpHeaders.Referer, "https://users.premierleague.com/accounts/login/")
        append(HttpHeaders.Accept, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
    }
    

内容的提问来源于stack exchange,提问作者lvm12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 20:26:08