SDKs

Kotlin

Android 與 JVM 上的 Kotlin 地道寫法

JVM/Android 上用 OkHttp + kotlinx.serialization,或者用 Coroutine 風格優先的 Ktor。下面示範 OkHttp。

Gradle

dependencies {
    implementation("com.squareup.okhttp3:okhttp:4.12.0")
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
}

設定

import okhttp3.*
import kotlinx.serialization.json.Json

private const val API = "https://openapi.thunderbit.com/openapi/v1"
private val JSON_MEDIA = "application/json".toMediaType()
private val client = OkHttpClient()

private fun request(path: String) = Request.Builder()
    .url("$API$path")
    .header("Authorization", "Bearer ${System.getenv("THUNDERBIT_API_KEY")}")

Distill 一個頁面

val body = """{"url": "https://thunderbit.com/playground"}"""
    .toRequestBody(JSON_MEDIA)

client.newCall(request("/distill").post(body).build()).execute().use { res ->
    if (!res.isSuccessful) error("HTTP ${'$'}{res.code}")
    println(res.body!!.string())
}

Extract 結構化資料

val body = """
{
  "url": "https://example.com/product/iphone-15-pro",
  "schema": {
    "type": "object",
    "properties": {
      "name":  { "type": "string" },
      "price": { "type": "number" }
    },
    "required": ["name", "price"]
  }
}
""".trimIndent().toRequestBody(JSON_MEDIA)

val res = client.newCall(request("/extract").post(body).build()).execute()

Coroutines + 批次

Android UI 場景請用 withContext(Dispatchers.IO) 包起來,或改用 Ktor 的 suspend client。批次任務則是先提交,再等 Webhook handler 回呼 —— 參見 Webhooks

官方 Kotlin SDK 開發中 —— 敬請期待。