Add dynamic number of parameters to http sampler - jmeter

I am looking for a way to add dynamic parameters[name:value] to http sampler.
i have found it for headers but not for parameters .
i have json file which contains method,parameters, headers,body, authorization according to the values i need to construct and send the http request.
I succeeded till setting HOST,PORT,PATH,HEADERS..
I want to set it for body,authorization,parameters before sending the http request.
The below is the groovy code in which i have parsed the json content to jsonparser from json parser i am setting the above http .
String fileContents = new File('../../src/resources/testInput.txt').text
def slurper = new JsonSlurper()
def inputjson = slurper.parseText fileContents
String httpmethod = inputjson.Method
sampler.setMethod(httpmethod);
inputjson.Headers.each{log.info it.each{
key,value -> log.info key
log.info value
sampler.getHeaderManager().add(new Header(key,value ));
}
}

Yea , I have found partial answer for query parameters.
inputjson.QueryParams.each{ it.each{
key,value ->
sampler.addArgument(key,value);
}

Related

request parameters got duplicated when forwarded between two tomcats

We have a Controller running on tomcat 8.5.32 which receives a POST request with query params
/{path_param}/issue?title=4&description=5
request body is empty
Then controller redirects this request to Spring Boot microservice with tomcat 9.0.27.
At line
CloseableHttpResponse result = httpClient.execute(request);
request.getURI().getQuery() equals&title=1&description=2
But when it arrives to microservice parameters are duplicated (title=[4,4]&description=[5,5]).
This is the code which redirects request to microservice
private static <T, U> T executePostRequest(String url, U body, HttpServletRequest httpServletRequest, Function<String, T> readValueFunction) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
URIBuilder uriBuilder = new URIBuilder(url);
httpServletRequest.getParameterMap().forEach((k, v) -> Arrays.stream(v).forEach(e -> uriBuilder.addParameter(k, e)));
HttpPost request = new HttpPost(uriBuilder.build());
CloseableHttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
handleResultStatus(result, json);
return readValueFunction.apply(json);
} catch (IOException | URISyntaxException e) {
...
}
}
I found that there was similar issue with jetty and it was fixed but did not find anything related to tomcat - and how it can be fixed.
I saw also this topic whith suggestion how to handle duplicated parameters in spring boot but i am wondering if anyone else experienced same issue and how did you resolve it if yes.
It's not a bug, it's a feature present in every servlet container.
The Servlet API does not require for the request parameters to have unique names. If you send a POST request for http://example.com/app/issue?title=1&description=2 with a body of:
title=3&description=4
then each parameter will have multiple values: title will have values 1 and 3, while description will have values 2 and 4 in that order:
Data from the query string and the post body are aggregated into the request
parameter set. Query string data is presented before post body data. For example, if
a request is made with a query string of a=hello and a post body of a=goodbye&a=
world, the resulting parameter set would be ordered a=(hello, goodbye, world).
(Servlet specification, section 3.1)
If you want to copy just the first value of the parameters use:
httpServletRequest.getParameterMap()//
.forEach((k, v) -> uriBuilder.addParameter(k, v[0]));

How to pass Bean shell processor variable in to HTTP Request body data in jmeter

I need to pass the Date format variable data from Bean shell processor to http request body
Below is my code and json where I passed variable data but it is not working
import java.text.SimpleDateFormat;
import java.util.Date;
Date enrolmentDate = new Date();
enrolmentDate.setDate(enrolmentDate.getDate());//+ ${__Random(1,50,)});
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm");
String formattedDate = df.format(enrolmentDate);
vars.put("StartDate",formattedDate);
log.info("########################"+formattedDate);
Below is the Http Request Body data
{
"articleId":""${ArticleId}",
"startDate":"${formattedDate}",
"endDate":"${Carttodates}"
}
When i run it Start date and end date is shown as ${formattedDate}, what will be the solution?
and in my JSON body data i want to send Start and End Date like "27/05/2019 14:34 "
Below is the Request I got
PUT data:
{
"articleId":"7694b207-936b-40b9-9c80-4b8097e67da1",
"startDate":"${formattedDate}",
"endDate":"${Carttodates}"
}
Change your request body to
{
"articleId":""${ArticleId}",
"startDate":"${StartDate}",
"endDate":"${Carttodates}"
}
The reason why this is required is because you are storing the date in "StartDate" variable in beanshell. Hence, you should use "StartDate" to access the value later in HTTP.
The other option is to store the value in "formattedDate" variable in beanshell and then you do not need to change it in HTTP request body.
You need to put formattedDate as the variable name also:
vars.put("formattedDate", formattedDate);

How to insert request body using BodyInserters in Spring5?

I am using Sping webflux module and create a WebClient, request uri and request body as follows:
// create webclient
WebClient wc3 = WebClient.builder()
.baseUrl("http://localhost:8080")
.defaultCookie("key", "val")
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
// set uri
WebClient.RequestBodySpec uri1 = wc3.method(HttpMethod.POST).uri("/getDocs");
// set a request body
WebClient.RequestBodySpec requestSpec1 = WebClient.create().method(HttpMethod.POST).uri("/getDocs")
.body(BodyInserters.fromPublisher(Mono.just("data")), String.class);
and when i am setting the request body, i am getting the following compilation error:
Multiple markers at this line
- Type mismatch: cannot convert from Mono<String> to P
- The method fromPublisher(P, Class<T>) in the type BodyInserters is not applicable for the arguments
(Mono<String>)
The java editor is showing just "Rename in file" as the suggestion.
I am not sure if i am using the BodyInserters perfectly or not. Please suggest.
It has to be like this
// set a request body
WebClient.RequestHeadersSpec<?> data = WebClient.create().method(HttpMethod.POST).uri("/getDocs")
.body(BodyInserters.fromPublisher(Mono.just("data"), String.class));

How to query SOAP based endpoint using Spring WS by passing pre generated SOAP Request instead of XML payload?

Need to query SOAP based endpoint using Sprint WS - but here instead of passing XML payload I will have pass a generated SOAP Request itself. I was using org.springframework.ws.client.core.WebServiceTemplate for this purpose right now ?
You can do the following:
ClientMessageCallBack _callBack =
new ClientMessageCallBack("yournamespaceuri/operationx");
final String _message =
"<ns1:operationx xmlns:ns1="yournamespaceuri"></ns1:operationx>";
StreamSource _source = new StreamSource(new StringReader(_message));
// the result will be output in the console
StreamResult _result = new StreamResult(System.out);
// suppose you have a reference to webServiceTemplate
webServiceTemplate.sendSourceAndReceiveToResult(_source,_callBack, _result);

Attempting to test rest service with multipart file

I am attempting to test a rest service I created. The service is a post.
I wanted to create a file to pass the parameters(including a multi-part file).
From there I am trying to call the service at this point.
Pretty sure the service that doesn't work. But when I call rest Service. I have a simple form that just passes in a couple values including the jpg.
Here is the code.
HttpMessageConverter bufferedIamageHttpMessageConverter = new ByteArrayHttpMessageConverter();
restTemplate.postForObject("http://localhost:8080/sendScreeenAsPostCard", uploadItem.getFileData(), String.class));
My method signature is:
ResultStatus sendScreenAsPostcard( #RequestParam MultipartFile image, #RequestParamString userId)
That is the error I am getting.
Could not write request: no suitable HttpMessageConverter found for request type [org.springframework.web.multipart.commons.CommonsMultipartFile]
You need to simulate a file upload, which requires a particular content type header, body parameters, etc. Something like this should do the trick:
// Fill out the "form"...
MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>();
parameters.add("file", new FileSystemResource("file.jpg")); // load file into parameter
parameters.add("blah", blah); // some other form field
// Set the headers...
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "multipart/form-data"); // we are sending a form
headers.set("Accept", "text/plain"); // looks like you want a string back
// Fire!
String result = restTemplate.exchange(
"http://localhost:8080/sendScreeenAsPostCard",
HttpMethod.POST,
new HttpEntity<MultiValueMap<String, Object>>(parameters, headers),
String.class
).getBody();

Resources