Setting cookie properly in fuel requests

1k Views Asked by At

I'm trying to set cookie to all get or post request after successful authentication. The authentication request returns response with Set-cookie header value of format

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

For web application I don't have to set anything, the xhr request automatically handles appending cookie. This cookie is also responsible for identifying user on back-end. I've read somewhere that cookie is just header with Cookie as key value.So after successful authentication, the Set-Cookie header is being read from response header of the format given using

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

Next this value is appended as header in each subsequent requests.

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
}

I can see the header being sent if I print headers in any post request as given below

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

this will print the same cookie previously set -

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

but the server returns 400 response status. The same api was also used to develop an app using react-native library. There, xhr requests automatically handles cookie management.

NB: I don't have access to back-end.

1

There are 1 best solutions below

0
On

I got this code to work for sending a single incoming 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 ->  ...  }