Below is an example of the Groovy Code that dynamically converts a Json content request into form data and sends an HTTP request.
import org.apache.http.HttpResponse
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.mime.MultipartEntityBuilder
import org.apache.http.entity.ContentType
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
import org.apache.http.message.BasicHeader
import groovy.json.JsonSlurper
def post = new HttpPost('http://test.com/api/v1/ServiceRequest/NewRequest')
def entityBuilder = MultipartEntityBuilder.create()
def boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW"
entityBuilder.setBoundary(boundary)
//JSON request is converted to JSON Object
def slurper = new JsonSlurper()
def params = slurper.parseText(requestBodyTextToTargetAPI)
//Form data is created by dynamically adding to the form data for each key and value in JSON.
params.each { key, value ->
entityBuilder.addTextBody(""+key, ""+value, ContentType.TEXT_PLAIN )
}
//If necessary, other header information is entered
post.addHeader(new BasicHeader('ApiKey', '##################################'))
post.setEntity(entityBuilder.build())
def client = HttpClients.createDefault()
def response
try {
response = client.execute(post)
//The flow can be interrupted with the result of the request and the response to the request can be directed by filling in the following variables,
//or the necessary business logic can be executed on the result.
statusCodeToTargetAPI=response.getStatusLine().getStatusCode();
requestErrorMessageToTargetAPI=EntityUtils.toString(response.getEntity());
} finally {
response?.close()
client?.close()
}
GROOVY