-2

I use curl to make HTTP POST request which makes a 302 redirect request. How can I parse the response of curl command to get the response header using Groovy?

PingPong
  • 123
  • 1
  • 3
  • 11
  • 1
    What have you try so far? Could you please post [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)? – Szymon Stepniak Jan 20 '18 at 11:00
  • 1
    https://stackoverflow.com/questions/34455505/how-to-post-json-in-groovy-with-standard-libraries and check the headers like https://stackoverflow.com/questions/7413801/how-to-check-programatically-if-url-of-page-is-redirecting – tim_yates Jan 20 '18 at 11:35
  • 1
    If you want process output via groovy, please use groovy libraries instead of curl. You will be able to write and test code better. – Jayan Jan 20 '18 at 11:51
  • @Jayan but for some reason I cannot make use of groovy libraries...I have to execute it using curl. – PingPong Jan 20 '18 at 12:18
  • 1
    The two links I just gave don't use libraries – tim_yates Jan 20 '18 at 12:33
  • @tim_yates It doesn't make use of curl either – PingPong Jan 20 '18 at 12:49
  • But how do you execute cURL request? Do you do it inside Groovy script or do you execute it from command line? Could you please elaborate and give us some code samples that describe what you do at the moment and what are your expectations. Otherwise it's very hard to follow. – Szymon Stepniak Jan 20 '18 at 13:16
  • 2
    Why do you want to use curl? What if curl isn't on the machine? What if you're deployed to a machine without curl? – tim_yates Jan 20 '18 at 14:16

1 Answers1

1

If you want to use Groovy to parse response headers from cURL command, you can try passing cURL output as a parameter to a Groovy script. Consider following script:

#!groovy

def location = (args[0] =~ 'Location: ([^\\n]+)\\n')?.getAt(0)?.getAt(1)

println "Location: ${location}"

It takes first parameter (args[0]) and extracts Location header value using regular expression and it prints what was extracted to console (in your case you can do different things with extracted value, this is just an example).

Let's say that this script is called location.groovy.

groovy location.groovy "`curl -i http://google.com`"

In this example I execute simple GET request to http://google.com. What is important - you have to double-quote what curl command returns, because it will contain \n characters that would mess up a little bit if not quoted. Also you have to use -i option to display headers and other stuff.

Of course you can also do something like:

CURL_RESULT=`curl -i http://google.com`
groovy location.groovy $CURL_RESULT

to split curl from groovy part. After running this script you will see something like that in the console:

Location: http://www.google.pl/?gfe_rd=cr&dcr=0&ei=2UZjWsygGYvEXs3WrRg
Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131