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

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

    ✅✅✅✅✅✅✅✅✅✅✅✅ Working Solution ✅✅✅✅✅✅✅✅✅✅✅✅

    While creating OkHttpClient that will be used for Retrofit.

    add an Interceptor like this.

     private val httpClient = OkHttpClient.Builder()
            .addInterceptor (other interceptors)
            ........................................
    
            //This Interceptor is the main logging Interceptor
            .addInterceptor { chain ->
                val request = chain.request()
                val jsonObj = JSONObject(Gson().toJson(request))
    
                val requestBody = (jsonObj
                ?.getJSONObject("tags")
                ?.getJSONObject("class retrofit2.Invocation")
                ?.getJSONArray("arguments")?.get(0) ?: "").toString()
                val url = jsonObj?.getJSONObject("url")?.getString("url") ?: ""
    
                Timber.d("gsonrequest request url: $url")
                Timber.d("gsonrequest body :$requestBody")
    
                chain.proceed(request)
            }
    
            ..............
            // Add other configurations
            .build()
    

    Now your every Retrofit call's URL and request body will be logged in Logcat. Filter it by "gsonrequest"

提交回复
热议问题