如何发送通过Retrofit Kotlin编码的具有URL形式的对象数组?

时间:2019-05-01 11:19:00

标签: android kotlin retrofit2

我想将编码的表单URL发送到服务器,但是参数需要对象数组

我尝试使用Retrofit的FieldMap并传递数据,但是当我尝试使用Postman时得到了不同的响应

Param需要通过

{
  "allowedStatus": "submit",
  "filters": [
    {
      "userId": "2"
    }
  ],
  "page": 1,
  "pageSize": 2
}

改造

@FormUrlEncoded
    @POST("ticket/status-list")
    fun getTicketStatusList(
        @Field("allowedStatus") allowedStatus: String,
        @FieldMap filters: HashMap<String, String>,
        @Field("page") page: Int,
        @Field("pageSize") pageSize: Int
    ): Observable<Response<TicketListModel>>

HashMap

val filters = HashMap<String, String>()
        filters["userId"] = "1"
        Log.e("fieldMap", filters.toString())
        getTicketStatusList("monitoring", filters, 1, 5)

我得到{}的结果,回复为200

2 个答案:

答案 0 :(得分:0)

请尝试这样:

val filters = HashMap<String, RequestBody>()
filters.put("userId", toRequestBody("2"))
getTicketStatusList("monitoring", filters, 1, 5)

还将“字符串”的哈希映射更改为“ RequestBody”

@FormUrlEncoded
    @POST("ticket/status-list")
    fun getTicketStatusList(
        @Field("allowedStatus") allowedStatus: String,
        @FieldMap filters: HashMap<String, RequestBody>,
        @Field("page") page: Int,
        @Field("pageSize") pageSize: Int
    ): Observable<Response<TicketListModel>>

以下方法将String转换为RequestBody

fun toRequestBody(value: String): RequestBody {
        return RequestBody.create(MediaType.parse("text/plain"), value)
}

答案 1 :(得分:0)

尝试以下方式:

data class Filters(var userId: String = "")

data class MyRequest(

        var allowedStatus: String = "",
        var filters: ArrayList<Filters>? = null,
        var page: Int = 0,
        var pageSize: Int = 0

        )

@POST("ticket/status-list")
fun getTicketStatusList(@Body request: MyRequest): Observable<Response<TicketListModel>>