How to store entire response and update it for nex

2019-08-22 17:25发布

问题:

Question: How to extract entire restAPI response and modify it with some values and use the updated response for sub-sequent rest call. I am using Jmeter

Question Scenario:

I have one POST call ex: "/check1/id1/post"
POST body :

{ 
                "test":"rest",
                "check" :{ 
                           "id":1,
                           "name": "xyz"
                         }
             }

POST call RESPONSE :

{ 
            "test":"rest",
            "check" :{ 
                       "id":1,
                       "name": "xyz"
                       "status":"updated"
                     }
         }

=====================================================================

QUESTION: Now, I have to use entire above RESPONSE in next POST Call body as below, BUT, I wanted to update "id" value as 2 and then need to POST rest call.

REST CALL: ------ > "/check1/id2/post" POST BODY as below : ------->

{ 
            "test":"rest",
            "check" :{ 
                       "id":2,
                       "name": "xyz"
                       "status":"updated"
                     }
         }

=============================================================

Can anyone please guide on this? , I am clueless about how to solve this issue?, I need to solve this using Jmeter.

回答1:

  1. To store entire response:

    • add Regular Expression Extractor as a child of the request which response you want to capture
    • configure it as follows:

      • Reference name: anything meaningful, i.e. response
      • Regular Expression: (?s)(^.*)
      • Template: $1$
  2. To replace 1 with 2 you can go for __strReplace() function like ${__strReplace(${response},1,2,)}. Note that you need to install Custom JMeter Functions bundle using JMeter Plugins Manager in order get it.


回答2:

You can do this using beanshell or JSR223 PreProcessor

Assuming a valid JSON

{ 
            "test":"rest",
            "check" :{ 
                       "id":1,
                       "name": "xyz",
                       "status":"updated"
                     }
         }

Here are the steps

  1. Add a JSR223 preprocessor to the 2nd post request.
  2. Add the following code to the preprocessor

    import groovy.json.JsonBuilder

    import groovy.json.JsonSlurper

    def slurped = new JsonSlurper().parse(prev.getResponseData())

    def builder = new JsonBuilder(slurped) builder.content.check.id = '2' vars.put("POSTDATA",builder.toPrettyString())

Above code will update ID value with 2 and stores the JSON in POSTDATA , you can use ${POSTDATA} to post the JSON FILE

In my pre processor i'm saving the response using prev.getResponseData() , that means this pre processor must included with the sampler right next to the first sampler.

For more information on beanshell Please follow this link