You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android端Kotlin如何通过POST请求发送JSONArray至API?

如何在Android中一次性发送JSONArray到API

嘿,我懂你这种困扰——循环发送单个JSONObject不仅效率低,还容易因为多次请求增加出错概率。其实不管是你试过的khttp、Fuel,还是现在主流的Retrofit、OkHttp,都支持直接把整个JSONArray作为请求体一次性发送,根本不用拆开来发。下面给你每个库的具体实现方式,你可以照着来:

1. 使用Retrofit(推荐,Android生态主流)

Retrofit是目前Android最常用的网络库,配置好后可以非常简洁地发送JSONArray:

首先定义你的API接口:

interface ApiService {
    // 直接将JSONArray作为请求体参数
    @POST("your-api-endpoint")
    suspend fun sendBatchData(@Body jsonArray: JSONArray): Response<ResponseBody>
}

然后初始化Retrofit并发起请求(记得在协程中执行网络操作):

// 初始化Retrofit实例
val retrofit = Retrofit.Builder()
    .baseUrl("https://your-api-base-url.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build()

val apiService = retrofit.create(ApiService::class.java)

// 构造你要发送的JSONArray
val dataArray = JSONArray().apply {
    put(JSONObject().apply {
        put("id", 1)
        put("name", "Test Item 1")
    })
    put(JSONObject().apply {
        put("id", 2)
        put("name", "Test Item 2")
    })
    // 继续添加更多JSONObject...
}

// 在协程中发送请求
CoroutineScope(Dispatchers.IO).launch {
    try {
        val response = apiService.sendBatchData(dataArray)
        if (response.isSuccessful) {
            // 请求成功,处理响应
            println("批量发送成功")
        } else {
            // 处理HTTP错误(比如4xx/5xx状态码)
            println("请求失败:${response.code()}")
        }
    } catch (e: Exception) {
        // 处理网络异常(比如无网络、连接超时)
        e.printStackTrace()
    }
}

2. 直接使用OkHttp(Retrofit底层,灵活可控)

如果不想用Retrofit,直接用OkHttp也能轻松实现:

val okHttpClient = OkHttpClient()

// 构造JSONArray
val dataArray = JSONArray().apply {
    // 填充数据...
}

// 将JSONArray转为请求体
val requestBody = RequestBody.create(
    MediaType.parse("application/json; charset=utf-8"),
    dataArray.toString()
)

// 构建请求
val request = Request.Builder()
    .url("https://your-api-base-url.com/your-api-endpoint")
    .post(requestBody)
    .build()

// 发送请求(后台线程执行)
CoroutineScope(Dispatchers.IO).launch {
    okHttpClient.newCall(request).execute().use { response ->
        if (!response.isSuccessful) {
            throw IOException("请求失败,状态码:${response.code()}")
        }
        // 处理响应内容
        val responseBody = response.body()?.string()
        println("响应内容:$responseBody")
    }
}

3. 使用Fuel库(你提到过的库,正确用法)

之前可能没找对方法,Fuel支持直接将JSON字符串作为请求体发送:

// 构造JSONArray
val dataArray = JSONArray().apply {
    // 填充数据...
}

// 发送POST请求
Fuel.post("https://your-api-base-url.com/your-api-endpoint")
    .header("Content-Type" to "application/json") // 必须指定Content-Type
    .body(dataArray.toString())
    .response { result ->
        val (_, response, error) = result
        if (error == null && response?.statusCode == 200) {
            // 请求成功
            println("批量发送成功")
        } else {
            // 处理错误
            println("请求失败:${error?.message}")
        }
    }

4. 使用khttp库(你试过的库,正确姿势)

khttp同样支持直接发送JSON数组,只要把JSON字符串作为请求体传入:

// 构造JSONArray
val dataArray = JSONArray().apply {
    // 填充数据...
}

// 发送POST请求
val response = khttp.post(
    url = "https://your-api-base-url.com/your-api-endpoint",
    headers = mapOf("Content-Type" to "application/json"),
    data = dataArray.toString()
)

// 处理响应
if (response.statusCode == 200) {
    println("批量发送成功,响应:${response.text}")
} else {
    println("请求失败,状态码:${response.statusCode}")
}

几个关键注意点:

  • 确保你的API后端已经支持接收application/json类型的JSONArray请求体,而不是只能接收单个JSONObject
  • 所有网络请求必须放在后台线程执行(比如协程、AsyncTask、线程池),绝对不能在主线程跑,否则会触发ANR(应用无响应)
  • 如果你的JSONArray数据量特别大(比如上万条),可以考虑分批次发送或者使用流式传输,但绝大多数场景下直接发送整个数组就足够了

内容的提问来源于stack exchange,提问作者Karl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:23:08