Cannot use CURL in GROOVY script to call REST PUT

I am trying to execute a simple PUT request using CURL. It just resides on the terminal, but cannot make it work in my Groovy script.

Here is a fragment of it: -

class Test { //Throws 415 Cannot Consume Content Type void testPUT () { println "curl -i -X PUT -H \"Content-Type: application/json\" -d '{\"Key1\":1, \"Key2\":\"Value2\"}' http://<hostname>/foo/".execute().text } // Works Perfectly Fine void testGET () { println "curl -i -X GET -H \"Content-Type: application/json\" http://<hostname>/foo".execute().text } } 

I also tried to enclose the command using triple quotes like: -

  """curl -i -X PUT -H "Content-Type:application/json" -d '{"Key1":1,"Key2":"Value2"}' http://<hostname>/foo""".execute().text 

All my attempts just give 415 Content type cannot be consumed

When I just use the curl command in the terminal window, both the PUT and GET methods work fine.

Am I missing something? Any help would be appreciated!

Thanks!

+4
source share
5 answers

Try using a list change on a line and see if this works:

 println ["curl", "-i", "-X PUT", "-H 'Content-Type:application/json'", "-d '{\"Key1\":1, \"Key2\":\"Value2\"}'", "http://<hostname>/foo/"].execute().text 

I had a similar problem and this was the only way to find a solution. Groovy will split the string into arguments in each space, and I suspect this disables Curl and the -H pair of arguments. By placing a string in a list, it combines each element as an argument.

+7
source

Based on Bruce's answer, you will also need to tokenize "-X PUT". Tested on groovy 2.3.6. ["curl", "-H", "Content-Type: application/json", "-H", "Accept: application/json", "-X", "PUT", "-d", data, uri].execute()

+3
source

It works in my terminal

 groovy -e "println 'curl -i -H \'Content-Type:application/json\' -XPUT -d \'{\"test\":4}\' http://google.fr/'.execute().text" 

If this does not work for you, this is most likely not a groovy problem.

0
source

Thanks xynthy for the list-changing hint, I still saw the scary "Content Type" application / x -www-form-urlencoded "not supported" with your example, but break -H and the content type strings.

This is confirmed by working in groovy 1.8:

 ["curl", "-H", "Content-Type: application/json", "-H", "Accept: application/json", "-X PUT", "-d", data, uri].execute().text 
0
source

First I installed the groovy post build plugin

https://wiki.jenkins-ci.org/display/JENKINS/Groovy+Postbuild+Plugin

Then I turned on the post w build groovy plugin in my post build settings of my jenkins work

and used the command

 "curl --request POST http://172.16.100.101:1337/jenkins/build".execute().text 

Here is my endpoint: http: 172.16.100.101:1337/jenkins/build

0
source

Source: https://habr.com/ru/post/1389583/


All Articles