BreadcrumbHomeResourcesBlog How To Send Groovy HTTP and HTTPS Requests June 7, 2021 How to Send Groovy HTTP and HTTPS RequestsOpen Source AutomationBy Sergey HorbanIn 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:Gson 2.8.4 - the downloaded JAR file must be added to JMeter, as shown in "How to Implement Data Driven Testing in your JMeter Test".To follow the example in this blog post, register on the site https://zapier.com and create WebHooks. We will be sending HTTPS requests through the created WebHooks.Table of Contents:Sending an HTTP / HTTPS POST Request in GroovySending a Groovy HTTP RequestRunning Your Groovy HTTP Request in BlazeMeter Sending an HTTP / HTTPS POST Request in GroovyIn 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 GroupRight Click -> Add -> Threads(Users) -> Thread Group2. Add a JSR223 SamplerThread Group -> Right Click -> Add -> Sampler -> JSR223 SamplerJSR223 Sampler -> Language GroovyIn 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));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 nameString 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 POSTMap 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 requestsetUri(url) - A method that sets the URL value to send a requestsetHeader(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 earlierbuild() - The final method that creates the HttpUriRequest objectString 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 sentHttpClientBuilder.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 requestList 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 responselog.info(Arrays.toString(test1)); - Displaying a request and response in the JMeter consoleAfter running the code for execution, we get the following result in the JMeter console: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.If we go to the web interface https://zapier.com, we will see the request that we sent, as shown in the image below.Now, this method can be added to the JAR file and called in JMeter, which reduces the time for creating tests.Start testing with the industry's most-trusted performance testing platform today! Test with BlazeMeter for FREE.Start Testing NowSending a Groovy HTTP RequestIn order to create your own method for sending an HTTP / HTTPS GET request, you need to do the following.1. Add a JSR223 SamplerThread Group -> Right Click -> Add -> Sampler -> JSR223 SamplerJSR223 Sampler -> Language GroovyIn 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));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: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.If we go to the web interface https://zapier.com, we will see the request that we sent, as shown in the image below.Want to learn more about JMeter? Sign up for our free BlazeMeter University.Running Your Groovy HTTP Request in BlazeMeterAfter 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: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 from BlazeMeter.START TESTING NOW Related Resources:The JMeter HTTP Request: How and When to Use It
Sergey Horban QA Specialist Sergey Horban is a QA Engineer with 3+ years of experience in automation and manual testing, bug-tracking and test management.