Work With Headers

Applies to ReadyAPI 3.56, last modified on October 29, 2024

You can use Groovy scripts to modify headers of requests, as well as get headers from responses. This topic describes how to use a Groovy script to work with HTTP headers.

Add header to request

Where to use

You can run this script as the RequestFilter.filterRequest event handler.

Example

The following code demonstrates how to add a custom HTTP header to requests from within the event handler:

Groovy

// Call the request headers
def headers = request.requestHeaders

// Create the custom header
headers.put( "X-tokenHeader", "value") // Replace values with those you need

// Add the custom header to request headers
request.requestHeaders = headers

Save response header value to property

Where to use

As a Groovy Script test step.

Example

The following code demonstrates how to save a response header value to a test case property:

Groovy

// Replace names of a test step and property with those you need

//Get the header value
def headerValue = testRunner.testCase.getTestStepByName("CreatePartner").httpRequest.response.responseHeaders["Location"]

// Save the value to a test case property
testRunner.testCase.setPropertyValue( "MyHeader", headerValue.toString() )

Add hashed authentication header

Where to use

You can run this script as the RequestFilter.filterRequest event handler.

Example

The following code demonstrates how to add an authentication header to requests from the event handler:

Groovy

import com.eviware.soapui.support.types.StringToStringMap
import java.io.UnsupportedEncodingException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.security.Timestamp
import java.util.Date

//Specify authentication data
apiKey = "123"
secret = "123"

// Get a timestamp
date= new java.util.Date()
timestamp = (date.getTime() / 1000)

// Get a hashed signature
signature = null

toBeHashed = apiKey + secret + timestamp
MessageDigest md = MessageDigest.getInstance("SHA-512")
byte[] bytes = md.digest(toBeHashed.getBytes("UTF-8"))
StringBuilder sb = new StringBuilder()
for(int i=0; i< bytes.length ;i++){
      sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1))
}

signature = sb.toString()

// Complete the header value
authHeaderValue = "EAN APIKey=" + apiKey + ",Signature=" + signature + ",timestamp=" + timestamp

// Obtain the list of request headers
headers = request.getRequestHeaders()

// Add a header to the request
StringToStringMap headermap = new StringToStringMap(headers)
if (headers.containsKeyIgnoreCase("authorization") ){
    headermap.replace("authorization", authHeaderValue)
} else {
    headermap.put("authorization", authHeaderValue)
}
 
request.requestHeaders = headermap

See Also

Handling Events
Groovy Scripting Samples
Scripting

Highlight search results