SDKs

Kotlin

Android 与 JVM 上的地道 Kotlin 写法

JVM/Android 用 OkHttp + kotlinx.serialization,或者用协程优先风格的 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()

协程 + Batch

Android UI 场景下用 withContext(Dispatchers.IO) 包一层,或者直接用 Ktor 的 suspend client。Batch 任务提交后,让 webhook handler 来处理回调 —— 详见 Webhooks

官方 Kotlin SDK 正在开发中,敬请期待。