Parth Tiwari
Parth Tiwari

Reputation: 486

How to add Token in Header in Jmeter?

When i run a thread group Loop Count with 2 for the first loop it works well but for second iteration it fails because in Header it add two times the Authorization Bearer token

I have created HTTP Request sampler named as “Login Request" inside of this sampler i added BeanShell PreProcessor’

import org.apache.jmeter.protocol.http.control.Header;
sampler.getHeaderManager().add(new Header("Authorization","Bearer " + vars.get("Token")));

It works well for 1 iteration but in second iteration it fails error shows there are two authorization in header

Upvotes: 2

Views: 5978

Answers (2)

Dmitri T
Dmitri T

Reputation: 168072

Amend your code to invoke removeHeaderNamed() function like:

import org.apache.jmeter.protocol.http.control.Header;
sampler.getHeaderManager().removeHeaderNamed("Authorization")
sampler.getHeaderManager().add(new Header("Authorization","Bearer " + vars.get("Token")));

this way you will get confidence that each time you're having only one Authorization header.

Also be aware that since JMeter 3.1 you should be using JSR223 Test Elements and Groovy language for scripting mainly because Groovy has much better performance comparing to Beanshell so consider migrating on next available opportunity (the same code will work fine)

Upvotes: 2

UBIK LOAD PACK
UBIK LOAD PACK

Reputation: 34526

You don’t need any Beanshell to do that

Just add a Header Manager and put in it :

  • Name: Authorization
  • Value: Bearer ${Token}

Upvotes: 7

Related Questions