This page explains a Groovy code example that dynamically converts a JSON content request to form data and makes an HTTP request.
Groovy Script
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)
//Dynamic addition to form data for each key and value in JSON
params.each { key, value ->
entityBuilder.addTextBody(""+key, ""+value, ContentType.TEXT_PLAIN)
}
//Other header information is entered if necessary
post.addHeader(new BasicHeader('ApiKey', '##################################'))
post.setEntity(entityBuilder.build())
def client = HttpClients.createDefault()
def response
try {
response = client.execute(post)
//By interrupting the flow with the result of the request, the response can be redirected by filling 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()
}
Explanation
This script performs the following operations:
- Parsing JSON: Parses the incoming JSON request body using
JsonSlurper.
- Creating Form Data: Creates an entity in multipart/form-data format using
MultipartEntityBuilder.
- Dynamic Field Addition: Adds each key-value pair in JSON to form data.
- Sending HTTP Request: Sends HTTP POST request with the created form data.
- Response Processing: Receives the result of the request and assigns it to necessary variables.
Usage Scenario
This script is used to convert a request in JSON format to form data format and send it to the backend service. It is particularly useful when the backend service expects data in form data format.
This script should be run on the request line (Request Policy) because it uses the requestBodyTextToTargetAPI variable.