JetBrains Space ヘルプ

HTTP リクエストを送信する

外部サービスへの HTTP リクエストの送信は、一般的な CI/CD タスクです。オートメーションでは、このタスクは通常次のように解決できます。

  1. 選択した HTTP クライアントを提供する Maven ライブラリを参照します (ライブラリは Maven Central でホストされている必要があります)。

  2. クライアントを使用して、kotlinScript コードブロックでリクエストを送信します。

例: 次のスクリプトは、icanhazdadjoke.com(英語) からランダムなジョークを取得し、それをジョブのログに出力します。この例では、OkHttp クライアントを使用します。

@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) } } }

より複雑な例: ビルドスクリプトは、time log-message データを含むログファイルを生成します。タスクは、このログを JSON 形式で外部サービスに送信することです。サービスには永久トークンによる認証が必要です。トークンはプロジェクトのシークレットとパラメーターに保存されます。この例では、Ktor HTTP クライアントを使用します。

@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 }