How to POST raw whole JSON in the body of a Retrofit request?

前端 未结 23 2341
面向向阳花
面向向阳花 2020-11-22 00:57

This question may have been asked before but no it was not definitively answered. How exactly does one post raw whole JSON inside the body of a Retrofit request?

See

23条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 01:40

    I found that when you use a compound object as @Body params, it could not work well with the Retrofit's GSONConverter (under the assumption you are using that). You have to use JsonObject and not JSONObject when working with that, it adds NameValueParams without being verbose about it - you can only see that if you add another dependency of logging interceptor, and other shenanigans.

    So what I found the best approach to tackle this is using RequestBody. You turn your object to RequestBody with a simple api call and launch it. In my case I'm converting a map:

       val map = HashMap()
            map["orderType"] = orderType
            map["optionType"] = optionType
            map["baseAmount"] = baseAmount.toString()
            map["openSpotRate"] = openSpotRate.toString()
            map["premiumAmount"] = premiumAmount.toString()
            map["premiumAmountAbc"] = premiumAmountAbc.toString()
            map["conversionSpotRate"] = (premiumAmountAbc / premiumAmount).toString()
            return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSONObject(map).toString())
    

    and this is the call:

     @POST("openUsvDeal")
    fun openUsvDeal(
            @Body params: RequestBody,
            @Query("timestamp") timeStamp: Long,
            @Query("appid") appid: String = Constants.APP_ID,
    ): Call
    

提交回复
热议问题