JSR223 Sampler - POST request

By xngo on July 14, 2022

Here is how to create a POST 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.

Currently, there is an issue with JMeter. Whenever it submits a POST request, it will always submit Content-Type in the headers. However, on the server side, if the POST request doesn't require Content-Type and you still submit it, it will return the error message Unsupported Media Type. To by pass this issue, write the code of the request itself like below instead of using JMeter.

// Create POST request with different properties.
    HttpURLConnection post = new URL("https://www.google.com/").openConnection();
    //    post.setRequestProperty("tenantId", vars.get("tenantId"));
    //    post.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 = post.getResponseCode();
    String responseMessage = post.getResponseMessage();
    if (responseCode.equals(201)) {
        String responseData = post.getInputStream().getText(); // Can only call once. Otherwise, it will throw "java.io.IOException: stream is closed"
    // Pass headers response back to JMeter:
    StringBuilder headers = new StringBuilder();
    String NL = System.getProperty("line.separator");
    Map<String, List<String>> map = post.getHeaderFields();
    for (Map.Entry<String, List<String>> entry : map.entrySet()) {
        headers.append(String.format("%s: %s%s", entry.getKey(), entry.getValue(), NL));


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.