首页 > 解决方案 > Retrofit POST with empty array

问题描述

I need to send a POST with Retrofit:

Retrofit.Builder()
  .baseUrl(API_BASE_URL)
  .addConverterFactory(
      GsonConverterFactory.create(
          GsonBuilder().serializeNulls().create()
      ))
  .client(okHttpClient)
  .build()

    @POST(endpoint)
    @FormUrlEncoded
    fun partialPickupsDelivery(
            @HeaderMap headers: Map<String, String>,
            @Field("userId") userId: String,
            @Field("purchaseIds[]") purchases: ArrayList<String>
    ): Call<ResponseBody>

The server is waiting something like this: purchaseIds=["1234", "2345", "3456"]

The problem comes when I try to send an empty array (not null) because the server is waiting: purchaseIds=[] But I'm sending only the first param userId (I think retrofit is removing the second one because the array is empty).

Is there any way to send purchaseIds=[]?

Thx

标签: androidretrofit2

解决方案


我终于找到了一个适合我的解决方案:

@POST(endpoint)
fun partialPickupsDelivery(
   @HeaderMap headers: Map<String, String>,
   @Body params: HashMap<String, Any>
): Call<ResponseBody?>

哪里params是:

val params = HashMap<String, Any>().apply {
    this["purchaseIds"] = destinationsId
    this["userId"] = deliverId
}

它是这样称呼的:

val call: Call<ResponseBody> =
      service.partialPickupsDelivery(
          headers,
          params
      )

我希望这可以帮助某人


推荐阅读