JSR223 Sampler - GET request

By xngo on July 14, 2022

Here is how to create a GET request using Groovy. The main idea is to create the request using HttpURLConnection class and then pass the results back to JMeter through SampleResult variable.

// Create GET request with different properties.
    HttpURLConnection get = new URL("https://www.google.com/").openConnection();
    get.setRequestMethod("GET");
    //    get.setRequestProperty("tenantId", vars.get("tenantId"));
    //    get.setRequestProperty("Authorization", props.get("Authorization"));
 
// Pass values back to JMeter:
//    - https://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html
//    - https://jmeter.apache.org/api/org/apache/jmeter/samplers/SampleResult.html
    int responseCode = get.getResponseCode();
    String responseMessage = get.getResponseMessage();
    SampleResult.setResponseCode(String.valueOf(responseCode));
    SampleResult.setResponseMessage(responseMessage);
 
    if (responseCode.equals(200)) {
        String responseData = get.getInputStream().getText(); // Can only call once. Otherwise, it will throw "java.io.IOException: stream is closed"
        SampleResult.setResponseData(responseData);
    }
 
    // Pass headers response back to JMeter:
    StringBuilder headers = new StringBuilder();
    String NL = System.getProperty("line.separator");
 
    Map<String, List<String>> map = get.getHeaderFields();
    for (Map.Entry<String, List<String>> entry : map.entrySet()) {
        headers.append(String.format("%s: %s%s", entry.getKey(), entry.getValue(), NL));
    }
    SampleResult.setResponseHeaders(headers.toString());

JSR223-GET-request-Script

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.