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

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

    Things required to send raw json in Retrofit.

    1) Make sure to add the following header and remove any other duplicate header. Since, on Retrofit's official documentation they specifically mention-

    Note that headers do not overwrite each other. All headers with the same name will be included in the request.

    @Headers({"Content-Type: application/json"})
    

    2) a. If you are using a converter factory you can pass your json as a String, JSONObject, JsonObject and even a POJO. Also have checked, having ScalarConverterFactory is not necessary only GsonConverterFactory does the job.

    @POST("/urlPath")
    @FormUrlEncoded
    Call myApi(@Header("Authorization") String auth, @Header("KEY") String key, 
                         @Body JsonObject/POJO/String requestBody);
    

    2) b. If you are NOT using any converter factory then you MUST use okhttp3's RequestBody as Retrofit's documentation says-

    The object will also be converted using a converter specified on the Retrofit instance. If no converter is added, only RequestBody can be used.

    RequestBody requestBody=RequestBody.create(MediaType.parse("application/json; charset=utf-8"),jsonString);
    
    @POST("/urlPath")
    @FormUrlEncoded
    Call myApi(@Header("Authorization") String auth, @Header("KEY") String key, 
                     @Body RequestBody requestBody);
    

    3) Success!!

提交回复
热议问题