Recently I was reading books (Programming Groovy and Groovy Recipes) about Groovy and recognized the potential in it. Using the JVM as a carrier makes the scripts available on all relevant platforms.
Actually it took some time to get the thing working, so I believe it might help others to check out my solution on curl in Groovy:
def curl(url, headers, fileName, outputFileName = 'out.log') {
def connection = new URL(url).openConnection()
connection.setRequestMethod(fileName ? 'POST' : 'GET')
headers.each() { key, value ->
connection.setRequestProperty(key ,value)
}
connection.doOutput = true
if (fileName) {
if (isPdf(fileName)) { // ***
connection.outputStream << new File(fileName).readBytes()
connection.outputStream.flush()
connection.outputStream.close()
} else {
connection.outputStream.withWriter() { writer ->
new File(fileName).eachByte() { writer.write it }
}
}
}
connection.connect()
new File(outputFileName).withOutputStream{ out ->
connection.content.eachByte() {out.write it}
}
connection.headerFields
}
The point is in the conditional statement marked with stars: according to the type of the file (binary or text) I had to handle posted data different ways.
No comments:
Post a Comment