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

前端 未结 23 2346
面向向阳花
面向向阳花 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:47

    This is what works me for the current version of retrofit 2.6.2,

    First of all, we need to add a Scalars Converter to the list of our Gradle dependencies, which would take care of converting java.lang.String objects to text/plain request bodies,

    implementation'com.squareup.retrofit2:converter-scalars:2.6.2'
    

    Then, we need to pass a converter factory to our Retrofit builder. It will later tell Retrofit how to convert the @Body parameter passed to the service.

    private val retrofitBuilder: Retrofit.Builder by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
    }
    

    Note: In my retrofit builder i have two converters Gson and Scalars you can use both of them but to send Json body we need to focus Scalars so if you don't need Gson remove it

    Then Retrofit service with a String body parameter.

    @Headers("Content-Type: application/json")
    @POST("users")
    fun saveUser(@Body   user: String): Response
    

    Then create the JSON body

    val user = JsonObject()
     user.addProperty("id", 001)
     user.addProperty("name", "Name")
    

    Call your service

    RetrofitService.myApi.saveUser(user.toString())
    

提交回复
热议问题