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
相关产品推荐
相关产品推荐

