June 7, 2021

How to Send Groovy HTTP and HTTPS Requests

Open Source Automation

In this article, we will explain how to send a Groovy HTTP request and HTTPS request and HTTPS in Apache JMeter™. This means using your own methods instead of creating them through the GUI. This is necessary when creating complex JMeter autotests because Groovy provides you with more flexibility. In addition, if there are changes in the API (for example, changing the URL or adding a parameter), you will only need to make the changes in one place.

Before creating methods for sending HTTP and HTTPS requests, you need to download the following JAR file:

Table of Contents:

Sending an HTTP / HTTPS POST Request in Groovy

In order to create your own method for sending an HTTP / HTTPS POST request, you need to do the following in JMeter.

1. Add a Thread Group

Right Click -> Add -> Threads(Users) -> Thread Group

writing http requests in groovy

2. Add a JSR223 Sampler

Thread Group -> Right Click -> Add -> Sampler -> JSR223 Sampler

JSR223 Sampler -> Language Groovy

groovy scripting in jmeter

In the JSR223 Sampler, add the following code example. You can adjust the code in your own script according to your specific needs.

importorg.apache.http.HttpHeaders;importorg.apache.http.client.config.RequestConfig;importorg.apache.http.client.methods.HttpUriRequest;importorg.apache.http.client.methods.RequestBuilder;importorg.apache.http.impl.client.HttpClientBuilder;importorg.apache.http.util.EntityUtils;importorg.apache.http.entity.StringEntity;importcom.google.gson.Gson;List<String>sendRequest(Stringurl,Stringmethod,Map<String,Object>body){RequestConfigrequestConfig=RequestConfig.custom().setConnectTimeout(2000).setSocketTimeout(3000).build();StringEntityentity=newStringEntity(newGson().toJson(body),"UTF-8");HttpUriRequestrequest=RequestBuilder.create(method).setConfig(requestConfig).setUri(url).setHeader(HttpHeaders.CONTENT_TYPE,"application/json;charset=UTF-8").setEntity(entity).build();Stringreq="REQUEST:"+"\n"+request.getRequestLine()+"\n"+"Headers: "+request.getAllHeaders()+"\n"+EntityUtils.toString(entity)+"\n";HttpClientBuilder.create().build().withCloseable{httpClient->httpClient.execute(request).withCloseable{response->Stringres="RESPONSE:"+"\n"+response.getStatusLine()+"\n"+"Headers: "+response.getAllHeaders()+"\n"+(response.getEntity()!=null?EntityUtils.toString(response.getEntity()):"")+"\n";System.out.println(req+"\n"+res);returnArrays.asList(req,res);}}}Map<String,Object>map=newLinkedHashMap<>();map.put("Param_1","Value_1");map.put("Param_2",Arrays.asList(1,2,3,4));map.put("Param_3",Arrays.asList("a","b","c"));Listtest1=sendRequest("https://hooks.zapier.com/hooks/catch/3320164/az95by","POST",map);log.info(Arrays.toString(test1));

adjusting your http request in jmeter

configuring a flexible http request in jmeter

The code shown above does the following:

import org.apache.http.HttpHeaders;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.http.entity.StringEntity;
import com.google.gson.Gson;
- Imports the classes required to send HTTP / HTTPS requests. These classes are imported from JAR files that are in JMeter.

List sendRequest(String url, String method, Map body) {
}
- Declaring a method for sending a HTTP / HTTPS request.

List - The type of data the method will return. A “List” is a data structure in which the data is displayed as a list. means that the list can only store data with a String type. In our case, the list will contain a request and a received response that will have the data type String.

sendPost - Method name

String url, String method, Map body - The method parameters. In other words, the variables needed to send the HTTP / HTTPS request. In our case, to send an HTTP / HTTPS request, the following variables must be passed to the method:

String url - the path by which to send the request. In our case, this is https://hooks.zapier.com/hooks/catch/3320164/az95by).

String method - the method of sending an HTTP / HTTPS request. In our case this is POST

Map body - body POST request. The request body will be passed as a variable with the data type Map . Map is a data structure called "Mapping", in which data is displayed as a key-value. indicates that the key must have a String data type, and the value can be an object with any data type. Since our request body will be sent in JSON format, the Map structure is similar to the JSON structure.

RequestConfig requestConfig = RequestConfig.custom()
                 .setConnectTimeout(2000)
                 .setSocketTimeout(3000)
         .build();
- Create an object that allows you to configure settings for the HTTP / HTTPS request.

.setConnectTimeout(2000) - A method that sets the time required to establish a connection to the host to which the request is sent. The time is specified in milliseconds (1 second = 1000 milliseconds). If the connection with the host is not established in 2 seconds (in our case with https://hooks.zapier.com), we will receive the following message: “org.apache.http.conn.ConnectTimeoutException: Connect to hooks.zapier.com failed: Connection timed out: connect”

.setConnectTimeout(3000) - A method that specifies the time during which the response from the host should be received. The time is specified in milliseconds. In our case, if no response is received within 3 seconds, then we will receive the following message: “java.net.SocketTimeoutException: Read timed out”

StringEntity entity = new StringEntity(new Gson().toJson(body), "UTF-8"); - Creating a StringEntity object that will contain the body of our request.

new Gson().toJson(body) - converting the value of the variable "body" to JSON format.

HttpUriRequest request = RequestBuilder.create(method)
                .setConfig(requestConfig)
                .setUri(url)
                .setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8")
                .setEntity(entity)
                .build();
  - Creating an object that will contain all the necessary parameters for sending the request.

setConfig(requestConfig) - A method that sets the value of the previously created configuration settings for the HTTP / HTTPS request

setUri(url) - A method that sets the URL value to send a request

setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8") - The method that sets the request headers. In our case, only the CONTENT_TYPE = "application/json header; charset = UTF-8" is set. If you need to set more than one header, then the setHeader () method is called as many times as necessary to add headers.

setEntity(entity) - A method that sets the value of the variable "entity" that was created earlier

build() - The final method that creates the HttpUriRequest object

String req = "REQUEST:" + "\n" + request.getRequestLine() + "\n" + "Headers: " +
                request.getAllHeaders() + "\n" + EntityUtils.toString(entity) + "\n";
- Forming the variable "req" with the data type String containing information about the request that is sent

HttpClientBuilder.create().build().withCloseable {httpClient ->
            httpClient.execute(request).withCloseable {response ->
                String res = "RESPONSE:" + "\n" + response.getStatusLine() + "\n" + "Headers: "
                        response.getAllHeaders() + "\n" +
                        (response.getEntity() != null ? EntityUtils.toString(response.getEntity()) : "") + "\n";

                System.out.println(req + "\n"  + res );

                return Arrays.asList(req, res);
            }
        }
-  Creating an httpClient object that will send the request; the formation of a response; displaying the request and the response to the cmd.
       

Map map = new LinkedHashMap<>();       
map.put("Param_1", "Value_1");      
map.put("Param_2", Arrays.asList(1,2,3,4));      
map.put("Param_3", Arrays.asList("a","b","c"));
- Creating the body of the request

List test1 = sendRequest("https://hooks.zapier.com/hooks/catch/3320164/az95by","POST", map); - Sending a request with specific values and generating the variable "test1" with the data type List, which will contain the request and response

log.info(Arrays.toString(test1)); - Displaying a request and response in the JMeter console

After running the code for execution, we get the following result in the JMeter console:

groovy test results, jmeter

The image above shows the request being sent and the response received.

The cmd will also display the sent request and the received response, as shown in the image below.

http and https requests in Groovy jmeter

If we go to the web interface https://zapier.com, we will see the request that we sent, as shown in the image below.

http requests in jmeter

Now, this method can be added to the JAR file and called in JMeter, which reduces the time for creating tests.

Sending a Groovy HTTP Request

In order to create your own method for sending an HTTP / HTTPS GET request, you need to do the following.

1. Add a JSR223 Sampler

Thread Group -> Right Click -> Add -> Sampler -> JSR223 Sampler

JSR223 Sampler -> Language Groovy

jmeter get request

In the JSR223 Sampler, add the following code example.

importorg.apache.http.HttpHeaders;importorg.apache.http.client.config.RequestConfig;importorg.apache.http.client.methods.HttpUriRequest;importorg.apache.http.client.methods.RequestBuilder;importorg.apache.http.impl.client.HttpClientBuilder;importorg.apache.http.util.EntityUtils;List<String>sendGet(Stringurl,Map<String,String>body){RequestConfigrequestConfig=RequestConfig.custom().setConnectTimeout(2000).setSocketTimeout(3000).build();RequestBuilderrequestBuilder=RequestBuilder.get().setConfig(requestConfig).setUri(url).setHeader(HttpHeaders.CONTENT_TYPE,"application/json;charset=UTF-8");body.forEach({key,value->requestBuilder.addParameter(key,value)});HttpUriRequestrequest=requestBuilder.build();Stringreq="REQUEST:"+"\n"+request.getRequestLine()+"\n"+"Headers: "+request.getAllHeaders()+"\n";HttpClientBuilder.create().build().withCloseable{httpClient->httpClient.execute(request).withCloseable{response->Stringres="RESPONSE:"+"\n"+response.getStatusLine()+"\n"+"Headers: "+response.getAllHeaders()+"\n"+(response.getEntity()!=null?EntityUtils.toString(response.getEntity()):"")+"\n";System.out.println(req+"\n"+res);returnArrays.asList(req,res);}}}Map<String,String>map=newLinkedHashMap<>();map.put("Param_1","Value_1");map.put("Param_2","Value_2");map.put("Param_3","Value_3");Listtest1=sendGet("https://hooks.zapier.com/hooks/catch/3320164/az95by",map);log.info(Arrays.toString(test1));

jmeter groovy code configuration

groovy scripting in jmeter

The code shown above is almost identical to the code for the sendRequest () method. A significant difference is the addition of parameters and values to the request, as shown below:

body.forEach({key, value -> requestBuilder.addParameter(key, value)}); - Adding parameters and values to a request.

After running the code for execution, we get the following result in the JMeter console:

http request demo jmeter

The image above shows the request being sent and the response received.

The cmd will also display the sent request and the received response, as shown in the image below.

http request in groovy tutorial

If we go to the web interface https://zapier.com, we will see the request that we sent, as shown in the image below.

sending requests in jmeter - a guide

Want to learn more about JMeter? Sign up for our free BlazeMeter University.

Running Your Groovy HTTP Request in BlazeMeter

After creating your own HTTP or HTTPS request, you can run your JMX script locally on your machine, or you can run it in the cloud through BlazeMeter. All you need to do is sign up to BlazeMeter, upload your JMX script, choose the number of users and locations you want to run from, and run the script.

By running your JMeter script in BlazeMeter, you can scale your tests, but also share tests and reports with team members and managers, and get advanced reporting, like this:

http requests in blazemeter

To get a taste of how BlazeMeter works, just put your URL in the box below, and your test will start in minutes. Ready for more? Request a live demo, here.

START TESTING NOW