1
votes

Can someone tell me how to access user defined variable inside an attached file of the HTTP Sampler?

What I did:
created an HTTP Requset Sampler (method POST);
created a variable myvar which is a JMeter 'Random Variable'.

Problem:
When I refer ${myvar} to populate an Http header it works but when I use it inside the file I am sending as the POST body it is not replaced but sent as it is ${myvar}.

Thanks in advance!

1

1 Answers

2
votes

1. As per reference 18.1.2 HTTP Request

Parameter Handling:
For the POST and PUT method, if there is no file to send, and the name(s) of the parameter(s) are omitted, then the body is created by concatenating all the value(s) of the parameters. This allows arbitrary bodies to be sent. The values are encoded if the encoding flag is set (versions of JMeter after 2.3).

So if you want to solve your problem with only standard HTTP Sampler functionality your have to use no file for your POST request and set ${myvar} as request param without name, as per above.


Since this approach seems not very applicable in your case, you may try also the following.

2. Rewrite your file to set ${myvar} to actual value before using in HTTP Request.

You can do this using either BSF PreProcessor / BeanShell PreProcessor - both attached directly to the "target" HTTP Request - or BSF Sampler / BeanShell Sampler - these should be placed before the "target" HTTP Request.

The code for the re-writing sampler may be like the following (beanshell):

// parsing params passed to script
String [] params = Parameters.split(",");

// setting values from params
String postFile = params[0];
String myVarValue = params[1];

StringBuilder data = new StringBuilder();
BufferedReader in = new BufferedReader(new FileReader(project.getProperty("basedir") +          
    System.getProperty("file.separator") + postFile));

char[] buf = new char[1024];
int numRead = 0;
while ((numRead = in.read(buf)) != -1) {
    data.append(buf, 0, numRead);
}
in.close();

// re-writting ${myvar} with actual value
String temp = data.toString().replaceAll("\\$\\{myvar\\}", myVarValue);

Writer out = new BufferedWriter(new FileWriter(project.getProperty("basedir") + 
    System.getProperty("file.separator") + postFile));
out.write(temp);
out.close();