Is it compulsory to use Bean Shell sampler?
If Yes:
Add Bean Shell Post processor to the http requests as a child.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.lang.reflect.*;
try {
String response = prev.getResponseDataAsString();
String pat = "<title>(.*?)</title>"; // change regular expression to match token
log.info("pattern used: " + pat);
Pattern r = Pattern.compile(pat, Pattern.DOTALL); // DOTALL to match new line ('.' matches new line)
Matcher m = r.matcher(response);
m.find();
//log.info("response " + response);
int count = m.groupCount();
log.info("matches " + count);
log.info("group " + m.group(1));
vars.put("token", m.group(1)); // to save the value into jmeter variables. in sub-sequent requests, you can refer the value by ${token}
}
catch (Throwable ex) {
log.error("Failed:", ex);
}
If not, following is the alternative (simple and efficient):
Short Answer: You have to capture the token from 1st and 2nd api responses from server, and you use it in subsequent requests.
You have to go through Regular Expression Extractor to perform this operation called Co-relation.
Long Answer:
Steps:
Identify the requests (as you mentioned 1st and 2nd api) in which responses, tokens are generated.
Add Regular Expression Extractor, as a child to these requests (1st and 2nd api requests), to capture the token from the response. Lets say, capture the value in variable "token_id1" from 1st request and "token_id2" from 2nd request.
- Identify subsequent requests in which token is used/sent. Replace all those values with ${token_id1} or ${token_id2} wherever applicable. This will make sure that Jmeter sent latest and active token values each time you run the script by capturing those values (tokens) sent by server using regular expression extractor and storing them into variables.
Note: If only token generated by either 1st or 2nd request api, is used by subsequent requests, then only capture that token (capture only on need basis).
References:
- How to extract multiple values with a regular expression in Jmeter
- https://guide.blazemeter.com/hc/en-us/articles/207421325-Using-RegEx-Regular-Expression-Extractor-with-JMeter
- http://artoftesting.com/performanceTesting/correlation.html