Search code examples
jmeter

Jmeter with multipart/form-data


In Jmeter i wanted to prepare multipart/form-data by using JSR223 PreProcessor groovy

i try using vars.put("formData", formData) like this

import org.apache.http.entity.ContentType
import org.apache.http.entity.mime.MultipartEntityBuilder
import org.apache.http.entity.mime.content.FileBody
import org.apache.http.entity.mime.content.StringBody
import org.apache.http.util.EntityUtils

def filePath = "path/to/file"
def file = new File(filePath)

def payload = "some payload"

def builder = MultipartEntityBuilder.create().setCharset(java.nio.charset.StandardCharsets.UTF_8)

builder.addPart("payload", new StringBody(payload, ContentType.TEXT_PLAIN))
builder.addPart("file", new FileBody(file, ContentType.APPLICATION_OCTET_STREAM, file.name))

def formData = builder.build()

vars.put("formData", formData)

and got error "No signature of method: org.apache.jmeter.threads.JMeterVariables.put() is applicable for argument types: (String, org.apache.http.entity.mime.MultipartFormEntity)" what should i do if i want to prepare multipart/form-data in script and then using it in HTTP Request?


Solution

    1. vars stands for JMeterVariables class instance. vars.put() function assumes that the 2nd argument is a String and you're trying to pass something else. If this is what you want you should use vars.putObject() instead. Or you need to convert the entity into a String first somehow

    2. I don't think you need to do this in Groovy at all, you can perform the multipart request using normal JMeter's HTTP Request sampler, you can put the "payload" into request parameters and the file to "Files Upload" and tick Use multipart/form-data box:

      enter image description here

      It also can be done programmatically using sampler shortcut for the HTTPSamplerProxy class

    See Top 8 JMeter Java Classes You Should Be Using with Groovy article for more information on the above and other JMeter API shorthands available for the JSR223 test elements