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

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

    For more clarity on the answers given here, this is how you can use the extension functions. This is only if you are using Kotlin

    If you are using com.squareup.okhttp3:okhttp:4.0.1 the older methods of creating objects of MediaType and RequestBody have been deprecated and cannot be used in Kotlin.

    If you want to use the extension functions to get a MediaType object and a ResponseBody object from your strings, firstly add the following lines to the class in which you expect to use them.

    import okhttp3.MediaType.Companion.toMediaType
    import okhttp3.RequestBody.Companion.toRequestBody
    

    You can now directly get an object of MediaType this way

    val mediaType = "application/json; charset=utf-8".toMediaType()
    

    To get an object of RequestBody first convert the JSONObject you want to send to a string this way. You have to pass the mediaType object to it.

    val requestBody = myJSONObject.toString().toRequestBody(mediaType)
    

提交回复
热议问题