Skip to main content
This page explains how to make API calls in x-www-form-urlencoded format using Groovy script policy.

Groovy Script

import groovy.json.JsonSlurper

try{
    String urlParameters = "url=parametreleri&burada=yerAlacak"
    byte[] postData = urlParameters.getBytes("UTF-8")
    int postDataLength = postData.length
    
    String request = "http://<SERVICE_IP>:30080/token"
    URL url = new URL(request)
    HttpURLConnection conn = (HttpURLConnection) url.openConnection()
    conn.setDoOutput(true)
    conn.setRequestMethod("POST")
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
    conn.setUseCaches(false)
    
    try{
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream())
        wr.write(postData)
        wr.close()
    }catch(Exception e){
        requestErrorMessageToTargetAPI = e.getMessage()
    }
    
    //do some logic with json response
    def json = conn.inputStream.withCloseable { inStream -> 
        new JsonSlurper().parse(inStream as InputStream) 
    }
    requestHeaderMapToTargetAPI.put("Authorization", "Bearer " + json.access_token)
    
    //or do some logic with text response
    String responseText = conn.inputStream.withCloseable { inStream -> 
        new BufferedReader(new InputStreamReader(inStream, "UTF-8")).getText() 
    }
}catch(Exception e){
    requestErrorMessageToTargetAPI = e.getMessage()
}

Explanation

This script performs the following operations:
  1. Form Data Preparation: Prepares URL parameters in application/x-www-form-urlencoded format.
  2. HTTP Connection: Creates a connection for HTTP POST request.
  3. Content-Type Setting: Sets the application/x-www-form-urlencoded Content-Type.
  4. Data Sending: Sends form data as POST body.
  5. Response Processing: Processes and uses the response in JSON or text format.

Usage Scenario

This script can be used in operations such as obtaining OAuth tokens. Parameters are sent in form data format and the returned access token is added to the header.
This script should be run on the request line (Request Policy) because it uses the requestHeaderMapToTargetAPI variable.