In JMeter, you can make HTTP requests with different settings such as using different verbs (GET, POST, etc) and sending data (through query string, request body). When it is time to adjust request in a slightly custom way before sending, it might be complicated in the first attempt. With BeanShell PreProcessor, it turns to be very easy.
In my case, I need to adjust request URI path with user variables so that it maps to correct request address. Sure, there might be some other ways to accomplish the same goal, but after experiencing how flexible it is to adjust request with BeanShell PreProcessor, I think it can satisfy lots of different cases at varied complex levels.
In my case, I need to make such a request:
In this request, the number coming after Client, 1, presents the client id. The value of parameter named Token presents the token value. Client id and token value are user variables in my JMeter project, which might come from preconfigured sources. Indeed, for simplicity, I added them directly just shown as below:
Here is how the request is set up:
As you can see from Path field, it is set as only Order, so without any additional configuration, the request would be like this:
Sure, this is not expected result so I add a BeanShell PreProcessor under the request, which is the one named “Adjust path”.
In the preprocessor, I place 4 lines to adjust request URI. Here is what I do line by line:
var sampler = ctx.getCurrentSampler();
Here, I access the current sampler object, which would be HTTPSampler in this case. You can find all details (methods, properties) about this sampler through the following link:
var path = sampler.getPath();
After getting HTTP sampler object, I retrieve the path value, then create a custom path value using user variables.
var customPath = "Client/" + vars.get("ClientId") + "/" + path + "?Token=" + vars.get("AccessToken");
vars.get(“Variable_name”) is the way to get the value of given variable by name.
Lastly, I set the new path as below:
With these lines, I can make the HTTP request as I want to be.
A few notes regarding the implemantation:
I am sure that it is not one of best samples to demonstrate extensibility and power of BeanShell PreProcessor in adjusting request and there might be more simple ways to do it to some extent. For example, if you set up the path field directly as below, you end up with the same result:
I find using BeanShell PreProcessor more clean as you embed the path construction logic and leave paths as simple as possible. Nevertheless, if you need to adjust request before sending, keep it in mind that you have a good friend, BeanShell PreProcessor, which offers pretty flexible options.