Optional Headers in http block


I am using Gatling 2.2.0. When I’m setting up an http request, I’d like to set an optional request header, based on a value set in the session.
What I thought I could do was to set a value in the session, then use the headers(Map[String, String]) , calling a function which would
detect the value in the session and either return a Map with a single entry, or an empty Map.

The problem I am having, is how to access the Session from a function which has been called from an http block.

Any help appreciated.



Something like this?

val scn = scenario(“Ft”)
.formParam(“password”, “${password}”)

.exec(http(“Get …”)
.header(“Authorization” , “${token}”)

There are a few ways to do this… this is the simplest if it’s just for a single request (check if someParameter exists in the session and act accordingly)

.doIfOrElse(session => { session(“someParameter”).asOption[String] != None}) {
} {

Or you could put the request in a function and call it with the headers to be used (will still need branching logic though).

Or if you need to consistently pass those headers once the session variable has been set in the session, your headers could be defined as a var Map, and then you could determine whether to add the optional item and if so, add it to that Map - and have your requests always use the headers contained within it.

Hope this gives you some ideas?


Thanks for this, Barry.

Can you give an example of the last option?
When I try to add an additional header to the http protocol:
httpProtocol.header(“Authorization”, “${access_token}”)
I get “Expression of type HttpProtocolBuilder doesn’t conform to expected type ChainBuilder”


Hi Alan,

I was thinking something along these lines - hope this helps.

var myHeaders = Map(
“Content-Type” → “application/json”,
“Accept” → “application/json”,

val someScenario = scenario(“exampleScenario”)
session => {
myHeaders += (“NewHeader” → “foo”) // Add a new header


Got it, thanks.

I was hoping to clean things up by modifying my http protocol after the first exec, so that I don’t have to keep adding the headers for any subsequent execs.
I understand now that the HttpProtocolBuilder is immutable and evaluated before the first exec, but I thought there might be a cleaner solution after this change:


Usualy I use Optional this way:

queryParam(“MY_PARAM”, _.get(“MY_PARAM”).asOption[String].getOrElseString)

As you can see, the example above is feeding an query parameter but you can use for a header as well.
I don’t believe that leaving a blank string in place is gonna be a problem.

Perfect! I didn’t think session was available when setting up http protocol, but seem to work just fine.


Sure, because this is a builder for something that WILL be executed for each virtual user.

So the session is available almost anywhere (with some limitations).

You can find more info here: http://gatling.io/docs/current/session/session_api/