SuperAPI AI Directory

kuikly-network-and-json

Coding & development

View repository

Updated 10-16 02:16

About this skill

Kuikly network requests

Contents

  • Core Guidelines
  • Workflow: HTTP Requests
  • Workflow: Binary Requests
  • Workflow: Parsing JSON
  • Reference resources

Core Guidelines

  • Get NetworkModule:
    • Kuikly DSL(Pager / ComposeView): call directly acquireModule<NetworkModule>(NetworkModule.MODULE_NAME) to get (throws an exception when not found), or use getModule<NetworkModule>(NetworkModule.MODULE_NAME) safe get (returns null when not found). Recommended: lazy cache the instance.
    • Compose DSL (in @Composable functions): via LocalActivity.current.getPager() get the Pager instance, then call pager.acquireModule<NetworkModule>(NetworkModule.MODULE_NAME). Inside a ComposeContainer class (non-@Composable context) you can call acquireModule。
  • Check success: in the callback first check success, and only when it is true is it safe to use data. On failure, use errorMsg and response.statusCode(note:Int? nullable) to troubleshoot.
  • Set timeout: httpRequest / httpRequestBinary can specify timeout(seconds), default 30.
  • Non-JSON response: the SDK automatically wraps it as {"data": "原始内容"}, retrieve via data.optString("data") .

Workflow: HTTP Requests

Method selection:

Scenario Method
Simple GET (no custom headers) requestGet(url, param, callback)
Simple POST (no custom headers) requestPost(url, param, callback)
Custom headers / Cookie / timeout httpRequest(url, isPost, param, headers, cookie, timeout, callback)

For the full method signatures and parameter descriptions, see NetworkModule API reference。

Get NetworkModule

Kuikly DSL (in Pager / ComposeView):

import com.tencent.kuikly.core.module.NetworkModule

// lazy 延迟初始化(推荐)
private val networkModule by lazy(LazyThreadSafetyMode.NONE) {
    acquireModule<NetworkModule>(NetworkModule.MODULE_NAME)
}

Compose DSL (in @Composable functions):

import com.tencent.kuikly.core.module.NetworkModule
import com.tencent.kuikly.compose.ui.platform.LocalActivity
import com.tencent.kuikly.core.pager.Pager

@Composable
fun MyScreen() {
    val pager = LocalActivity.current.getPager() as Pager
    val networkModule = pager.acquireModule<NetworkModule>(NetworkModule.MODULE_NAME)
    // 使用 networkModule 发起请求...
}

Compose DSL (inside a ComposeContainer class):

@Page("MyComposePage")
class MyComposePage : ComposeContainer() {
    // ComposeContainer 继承自 Pager,可直接调用 acquireModule
    private val networkModule by lazy(LazyThreadSafetyMode.NONE) {
        acquireModule<NetworkModule>(NetworkModule.MODULE_NAME)
    }
}

GET request

networkModule.requestGet(
    "https://example.com/api/data",
    JSONObject().apply { put("key", "value") }
) { data, success, errorMsg, response ->
    if (success) {
        val name = data.optString("name")
        val count = data.optInt("count")
    } else {
        val statusCode = response.statusCode // Int? 可能为 null
    }
}

POST request

networkModule.requestPost(
    "https://example.com/api/submit",
    JSONObject().apply {
        put("username", "test")
        put("password", "123456")
    }
) { data, success, errorMsg, response ->
    if (success) {
        val result = data.optString("result")
    }
}

Generic request (httpRequest)

networkModule.httpRequest(
    url = "https://example.com/api/data",
    isPost = true,
    param = JSONObject().apply { put("id", 1) },
    headers = JSONObject().apply {
        put("Content-Type", "application/json")
        put("Authorization", "Bearer token")
    },
    cookie = "session_id=abc123",
    timeout = 30
) { data, success, errorMsg, response ->
    // response.statusCode   - HTTP 状态码(Int?)
    // response.headerFields - 响应头(JSONObject)
    if (success) { /* 处理数据 */ }
}

Workflow: Binary Requests

Method selection:

Scenario Method
Download binary (GET) requestGetBinary(url, param, callback)
Upload binary (POST) requestPostBinary(url, bytes, callback)
Custom headers / Cookie / timeout httpRequestBinary(url, isPost, bytes, param, headers, cookie, timeout, callback)

requestPostBinary inside param pass null. If you need to pass both a binary body and query parameters, use httpRequestBinary。

Download binary (GET)

networkModule.requestGetBinary(
    "https://example.com/file.png",
    JSONObject()
) { data, success, errorMsg, response ->
    if (success) {
        val fileBytes: ByteArray = data
    }
}

Upload binary (POST)

networkModule.requestPostBinary(
    "https://example.com/upload",
    imageBytes
) { data, success, errorMsg, response ->
    if (success) {
        val responseBytes: ByteArray = data
    }
}

Generic binary request (httpRequestBinary)

networkModule.httpRequestBinary(
    url = "https://example.com/api/binary",
    isPost = true,
    bytes = uploadBytes,
    param = JSONObject().apply { put("type", "image") },
    headers = JSONObject().apply { put("Content-Type", "application/octet-stream") },
    cookie = "session_id=abc123",
    timeout = 60
) { data, success, errorMsg, response ->
    if (success) {
        val responseBytes: ByteArray = data
    }
}

Workflow: Parsing JSON

Use the opt* series of methods to read safely (does not throw exceptions, returns default values).

For the complete JSONObject/JSONArray API list, see JSON API reference。

Core usage examples

val jsonObj = JSONObject(jsonString)

// 安全读取(不存在时返回默认值)
val str = jsonObj.optString("key")             // 默认 ""
val num = jsonObj.optInt("key")                // 默认 0
val innerObj = jsonObj.optJSONObject("nested")  // JSONObject?
val array = jsonObj.optJSONArray("list")        // JSONArray?

// 写入
jsonObj.put("key", "value")

// 遍历所有 key
for (key in jsonObj.keys()) { /* ... */ }

JSONArray iteration

val jsonArr = jsonObj.optJSONArray("list") ?: JSONArray()
for (i in 0 until jsonArr.length()) {
    val item = jsonArr.optJSONObject(i) ?: continue
    val name = item.optString("name")
}

Reference resources