Forum Discussion
stewmoon,
I had a situation where I needed to change the header in every GET request (from inside a groovy script at RequestFilter.filterRequest) from json to application/x-www-form-urlencoded. I did not use the headers.clear() operation but had similar operations that the URLs above explain (message 4). I would guess when assigning headers to request.requestHeaders it is doing a replacement. Here is what I did
def headers = request.requestHeaders log.info "\n\n\n\n" log.info " This is the RequestFilter.filterRequest Groovy Script running now " log.info "\n\n\n\n" String theMethod = context.getProperty("httpMethod").toString()
String theGet = new String("GET") if (theMethod.substring(0, 3) == theGet) { log.info ".....Found a GET!!!!!!!!!!!!!" // In case of a GET request I did the following log.info "headers (right before adding the urlencoded content type): " + headers log.info "headers size now: " + (request.requestHeaders.size()) headers.put( "Content-Type", "application/x-www-form-urlencoded") // Replace values with those you need log.info "Added Content-Type: application/x-www-form-urlencoded" request.requestHeaders = headers log.info "headers size now: " + (request.requestHeaders.size()) // display the header log.info "actual header is " + request.requestHeaders }
- stewmoon8 years agoOccasional Contributor
Hello Bill and nmrao,
To clarify it was really two questions:
Question 1:
What is the code that Deletes an existing Header.
Question2:
What is the code that Modifys an existing Header.
From looking at the answers it appears I will first need to delete then re-add the header if I want to modify it.Both of my questions were answered through this thread.
Thank you.- Nastya_Khovrina8 years ago
Alumni
Hi Stewart,
stewmoon wrote:
Question 1:
What is the code that Deletes an existing Header.Please see the example of deleting the X-tokenHeader header (if it exists):
if (request.requestHeaders.containsKey("X-tokenHeader")) { def headers = request.requestHeaders headers.remove("X-tokenHeader") request.requestHeaders = headers }
stewmoon wrote:
Question2:
What is the code that Modifys an existing Header.You can try adding the if condition in the script, please see an example for the Content-Type header:
def header =request.getRequestHeaders() header.each { key,val -> if (key == "Content-Type"){ header['Content-Type'] = 'application/json' } else{ headers.put("Content-Type", 'application/json') request.requestHeaders = headers } }
I hope this helps!