Send HTTP Requests
Sending an HTTP request to an external service is a common CI/CD task. In Automation, this task can be generally solved as follows:
Reference a Maven library that provides an HTTP client of your choice (the library must be hosted on Maven Central).
Use the client to send requests in a kotlinScript
code block.
For example, the following script gets a random joke from icanhazdadjoke.com and prints it to the job's log. In this example we use the OkHttp client.
@file:DependsOn("com.squareup.okhttp:okhttp:2.7.4", "org.json:json:20200518")
import com.squareup.okhttp.*
import org.json.JSONObject
job("Example") {
container(image = "amazoncorretto:17-alpine", displayName = "Get random joke") {
kotlinScript {
val client = OkHttpClient()
val request = Request.Builder()
.url("http://icanhazdadjoke.com")
.addHeader("Accept", "application/json")
.build()
val response = client.newCall(request).execute()
val jData = response.body().string()
val jObject = JSONObject(jData)
val joke = jObject.get("joke").toString()
println(joke)
}
}
}
More complex example: A build script generates a log file with the time log-message
data. The task is to send this log to an external service in the JSON format. The service requires authentication with a permanent token. The token is stored in the project's Secrets & Parameters. In this example we use the Ktor HTTP client.
@file:DependsOn("io.ktor:ktor-client-core:1.6.0", "io.ktor:ktor-client-gson:1.6.0")
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.http.*
job("Example") {
container(image = "amazoncorretto:17-alpine", displayName = "Send JSON logs"){
// get auth token from a project secret
env["TOKEN"] = Secrets("auth-token")
kotlinScript {
// emulate the work of build script by creating a log file
val file = java.io.File("logs.txt")
file.writeText("""
12:00:01 Log message 1
12:00:02 Log message 2
12:00:02 Log message 3
""".trimIndent())
// convert file to object list
val log = readLogFile(file)
// create a Ktor HTTP client
val client = HttpClient() {
// install JsonFeature to serialize the data we send
install(io.ktor.client.features.json.JsonFeature) {
// use the Gson serializer
serializer = io.ktor.client.features.json.GsonSerializer()
}
}
// get auth token from env var
val token = System.getenv("TOKEN")
// send a POST request to external service
client.post<Unit>("https://external-service.url") {
headers {
// add auth header with bearer token
append(HttpHeaders.Authorization, "Bearer $token")
}
// the client will serialize log into json
contentType(ContentType.Application.Json)
body = log
}
}
}
// external service receives the payload:
// [{"time":"12:00:01","msg":"Log message 1"},
// {"time":"12:00:02","msg":"Log message 2"},
// {"time":"12:00:02","msg":"Log message 3"}]
}
// representation of a log line
data class LogEntry(val time: String, val msg: String)
fun readLogFile(file: java.io.File): List<LogEntry> {
val logLines = file.readLines()
val result = mutableListOf<LogEntry>()
logLines.forEach {
val line = it.split(" ", limit = 2)
val entry = LogEntry(line[0], line[1])
result.add(entry)
}
return result
}
Last modified: 15 December 2023