Set headers in a groovy post request

21,837

I'm surprised that specifying the headers map in the post() method itself isn't working. However, here is how I've done this kind of thing in the past.

def username = ...
def password = ...
def questionId = ...
def responseText = ...

def client = new RestClient('https://myhost:1234/api/')
client.headers['Authorization'] = "Basic ${"$username:$password".bytes.encodeBase64()}"

def response = client.post(
    path: "/question/$questionId/response/",
    body: [text: responseText],
    contentType: MediaType.APPLICATION_JSON_VALUE
)

...

Hope this helps.

Share:
21,837
The Strong Programmer
Author by

The Strong Programmer

Java and Grails developer with 10 years of professional experience.

Updated on March 01, 2020

Comments

  • The Strong Programmer
    The Strong Programmer about 4 years

    I need to set a header in a post request: ["Authorization": request.token] I have tried with wslite and with groovyx.net.http.HTTPBuilder but I always get a 401-Not authorized which means that I do cannot set the header right. I have also thought of logging my request to debug it but I am not able to do that either. With wslite this is what I do

            Map<String, String> headers = new HashMap<String, String>(["Authorization": request.token])
        TreeMap responseMap
        def body = [amount: request.amount]
        log.info(body)
        try {
            Response response = getRestClient().post(path: url, headers: headers) {
                json body
            }
            responseMap = parseResponse(response)
        } catch (RESTClientException e) {
            log.error("Exception !: ${e.message}")
        }
    

    Regarding the groovyx.net.http.HTTPBuilder, I am reading this example https://github.com/jgritman/httpbuilder/wiki/POST-Examples but I do not see any header setting... Can you please give me some advice on that?