首页 > 解决方案 > 在燃料请求中正确设置 cookie

问题描述

我正在尝试将 cookie 设置为成功验证后的所有获取或发布请求。身份验证请求返回带有Set-cookie格式头值的响应

[accesstoken=sample_token; Version=1; Comment=secured; Domain=test.com; Max-Age=172800000; Expires=Mon, 07-Apr-2025 10:55:18 GMT; Path=]

对于 Web 应用程序,我不必设置任何内容,xhr 请求会自动处理附加的 cookie。此 cookie 还负责在后端识别用户。我在某处读到 cookie 只是Cookie作为键值的标头。因此,在成功验证后,Set-Cookie将从使用给定格式的响应标头中读取标头

var cookeis = response.headers.get("Set-Cookie").toString()

接下来,此值将作为标头附加到每个后续请求中。

fun _POST(ctx: Context, path: String, query: List<Pair<String, String?>>): Request {
  var fuel = Fuel.post(ctx.getString(baseID)+path, query)
  val accesstoken = getCookie(ctx)

  when(accesstoken!=null){
    true ->  fuel = fuel.set(com.github.kittinunf.fuel.core.Headers.COOKIE,accesstoken)
    false -> {}
  }
return fuel
}

如果我在任何发布请求中打印标题,我可以看到正在发送的标题,如下所示

val (request, response, result) = _POST(this@MainActivity, getString(R.string.API_MY_DATA), listOf("date" to currentDate))
                .also { println(it.headers.toString()) }
                .response()

这将打印之前设置的相同 cookie -

[accesstoken=sample_token; Version=1; Comment=secured; Domain=test.com; Max-Age=172800000; Expires=Mon, 07-Apr-2025 10:55:18 GMT; Path=]

但服务器返回 400 响应状态。相同的 api 还用于使用react-native库开发应用程序。在那里,xhr 请求会自动处理 cookie 管理。

注意:我无权访问后端。

标签: androidcookiesfuel

解决方案


我得到了这个代码来发送一个传入的cookie:

// response being from a previous Fuel POST
val cook = response.headers["Set-Cookie"].first()

Fuel.get("https://mundraub.org/node/add/plant").header(Headers.COOKIE to cook)
.responseString { request2, response2, result2 ->  ...  }

推荐阅读