Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set headers in a groovy post request

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?

like image 316
The Strong Programmer Avatar asked Oct 12 '25 22:10

The Strong Programmer


1 Answers

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.

like image 133
Jon Peterson Avatar answered Oct 15 '25 16:10

Jon Peterson