Forum Discussion

bkbn16's avatar
bkbn16
Contributor
9 years ago

Need to update/set Header Values through groovy scripting

Hi,   I have created a REST Mock response. To invoke the response; I have the URI and request body.    def Accept = mockRequest.getRequest().getHeader("Accept")  log.info(Accept)   This is giv...
  • bkbn16's avatar
    bkbn16
    9 years ago

    Hi rupert,

     

    Thanks for replying back again. This is how I need to do ...

     

    I first created a Empty Project > Mock Service. Underneath this, created a Mock action 'POST' (resource path being: /rest/login). Underneath this, a JSON mock response added. So when I run the mock service with resource path I get the json mock response directly. Now, in addition to the resource path I am trying to add a request body (also in Json), something like this {"username": "admin", "password": "admin"}. 

    Then, I wrote a script which must alter the Accept Header Field in request body, as well as append the json message to the request body and calculate the Content-Length the request body.

     

    import java.lang.*
    import java.util.*
    import java.io.*
    import java.net.*
    import groovy.lang.*
    import groovy.util.*
    import javax.servlet.http.*
    def groovyUtils=new com.eviware.soapui.support.GroovyUtils(context)
    import groovy.json.JsonSlurper
    import com.eviware.soapui.model.iface.*
    log.info("response="+mockRequest)
    def query = mockRequest.getRequest()
    //log.info(query)

    def ContentType = mockRequest.getRequest().getHeader("Content-Type").toString()
    //log.info(ContentType)
    def ContentLength = mockRequest.getRequest().getHeader("Content-Length").toString()
    //log.info(ContentLength)
    def Accept = mockRequest.getRequest().getHeader("Accept").toString()
    //log.info(Accept)
    def method = mockRequest.getMethod().toString()
    //log.info(method)
    def path = mockRequest.getPath().toString()
    //log.info(path)

    jsonAsText = '''{ "username": admin, "password": admin, "device-token": AA}'''
    //log.info(jsonAsText)

    def RequestBody = method +" " +path + '\n' + "Content-Type: "+ContentType + '\n' + "Accept: "+Accept + '\n' + "Content-Length: "+ContentLength + '\n' + '\n' + jsonAsText
    log.info(RequestBody)

    RequestBody.setRequestContent
    return "JSON"

     

    How do I alter the request body before returning the JSON response ? Thanks in advance.