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

Android-Kotlin中通过POST提交数组数据的实现方法问询

实现Retrofit POST请求提交指定City数据示例

我来帮你搞定这个数据构建和提交的问题,按照你需要的cityId=1对应detail=["1.1","1.2"]、cityId=2对应detail=["2.1","2.2"]的要求,下面是完整的实现示例:

1. 构建City对象与CityRequest请求体

首先我们需要创建符合要求的City实例,再把它们封装到CityRequest的列表中:

// 构建第一个City对象:cityId=1,detail包含"1.1"和"1.2"
val city1 = City(
    cityId = 1,
    detail = listOf("1.1", "1.2")
)

// 构建第二个City对象:cityId=2,detail包含"2.1"和"2.2"
val city2 = City(
    cityId = 2,
    detail = listOf("2.1", "2.2")
)

// 把两个City对象打包成请求体
val cityRequest = CityRequest(
    listCity = listOf(city1, city2)
)

2. 完善sendDataCity函数实现

接下来在你的sendDataCity函数里,调用Retrofit接口发送请求即可,记得处理协程中的异常(比如网络错误):

suspend fun sendDataCity(retrofitApi: YourRetrofitApiInterface) {
    try {
        val response = retrofitApi.sendCityContent(cityRequest)
        // 处理接口响应
        if (response.isSuccessful) {
            val cityResponse = response.body()
            cityResponse?.let {
                // 根据返回的code、status、message做业务逻辑处理
                println("请求成功:${it.message}")
            }
        } else {
            println("请求失败,错误码:${response.code()}")
        }
    } catch (e: Exception) {
        // 捕获网络异常或其他报错
        println("请求出错:${e.message}")
    }
}

小优化提示

你的Retrofit API接口里,sendCityContent用了suspend关键字但返回值是Call<CityResponse?>,其实Retrofit支持协程直接返回Response<CityResponse?>,这样代码会更简洁,推荐修改接口定义:

@Headers("Content-Type: application/json")
@POST("city")
suspend fun sendCityContent(@Body listCity: CityRequest?): Response<CityResponse?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 15:38:02