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 giving me /* as response in console, but I need to update it as "application/json"
def Method = mockRequest.getRequest()
log.info(Method)
This is giving me ...
POST rest/login
Accept: /*
Content-Type: application/json
Content-Length: 8
......
But what I want is along with the request body like
POST rest/login
Accept: application/json
Content-Type: application/json
Content-Length: [length of this message]
{'username':'admin', 'password': 'admin'}
How can I update or set the request header and the body through the script ?
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.