I have a JMeter HTTP-Request element which performs a POST call like:
{
"id" : 1,
"name" : "me"
}
I want to load this request body on a BeanShell PreProcessor and modify the name field, how can I achieve this?
Answering my own question:
Get Request Body:
String requestBody = sampler.getArguments().getArgument(0).getValue();
Modify request(In my case I modified it as a parsed JSONObject)
Set the modified request body into the current request:
sampler.getArguments().getArgument(0).setValue(modifiedRequestObject.toString());
Since JMeter 3.1 you're supposed to be using JSR223 Test Elements and Groovy language for scripting so I would recommend re-considering your "Beanshell" approach.
Here is a piece of sample Groovy code showing how you can amend the request:
def payload = new groovy.json.JsonSlurper().parseText(sampler.getArguments().getArgument(0).getValue())
payload.name = 'some new name'
sampler.getArguments().clear()
sampler.addNonEncodedArgument('', new groovy.json.JsonBuilder(payload).toPrettyString(), '')
sampler.setPostBodyRaw(true)
More information: