android - 在燃料请求中正确设置 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 管理。
注意:我无权访问后端。
解决方案
我得到了这个代码来发送一个传入的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 -> ... }
推荐阅读
- sql - SQL Server 2014:将两个逗号分隔的字符串转换为两列
- xamarin - PushPageModel 在 Xamarin 中的简单按钮上不起作用
- android - sweet-alert-dialog 中的更改进度对话框
- amazon-web-services - 使用 Powershell 从 s3 下载最近 24 小时的文件
- python - pandas协方差矩阵大于1的元素
- kotlin - 构建自动填充服务的 parseStructure 方法
- bevy - 如何在 bevy 0.5.0 中消除使用 commands.spawn_bundle() 生成的实体
- r - 如何将我的 resid() 输出显示为普通数据框?
- laravel - 生产服务器上的 Vuejs 和 laravel 7 api 未经授权的问题
- javascript - 选择值并将其插入新行?