I need to add json as multipart body part to "multipart/form-data" request using groovy.

I can do this using file attachments:

testRunner.testCase
          .testSteps["/job/result"]
          .getHttpRequest()
          .attachBinaryData(json.toString().getBytes(), "application/json").contentID = "info"

My problem is "attachBinaryData" creates a temp file per request. It is not good for load tests :)

Is there other possibility to add body parts, without file attachments?

something like :

testRunner.testCase
              .testSteps["/job/result"]
              .getHttpRequest()
              .addBodyPart("application/json", json.toString())

P.S. it must be the "add", because request has also one static attachment.

2 Answers

0
DSmelanskij On Best Solutions

Have found a solution using https://github.com/jgritman/httpbuilder

def http = new HTTPBuilder(serviceEndPoint)
def scanResultFile = new File(testRunner.testCase.getPropertyValue("ScanResultFile"))

http.request( POST ){ req ->

    headers.'Connection' = 'Keep-Alive'
    headers.'User-Agent' = 'SoapUI 4.5.1'
    requestContentType = 'multipart/form-data'

    ByteArrayBody bin = new ByteArrayBody(scanResultFile.readBytes(), "application/octet-stream", "jobResult");
    StringBody info = new StringBody(testRunner.testCase.getPropertyValue("JsonScanResult"), "application/json", java.nio.charset.StandardCharsets.UTF_8);

    MultipartEntity entity = new MultipartEntity()
    entity.addPart("info", info);
    entity.addPart("jobResult", bin)
    req.entity = entity
}
0
albciff On

If you want to add a json to your request as a multipart/form-data using groovy script testStep you can use the follow code:

def jsonStr = "{'id':'test','someValue':'3'}"

def testStep = context.testCase.testSteps["/job/result"]
// set the content for the request
testStep.getHttpRequest().setRequestContent(jsonStr)
// and set the media type 
testStep.testRequest.setMediaType('application/json')
// if you want to send as a multipart/form-data then use follow line instead
// testStep.testRequest.setMediaType('multipart/form-data')

This results in a request configured as follows:

enter image description here

Hope it helps,