How to get raw json response of Retrofit in Kotlin?

Viewed 18548

I am new to Kotlin and Retrofit. I want to call a base URL through Retrofit and print the raw JSON response. What would be the simplest minimal configuration?

Let's say,

base url = "https://devapis.gov/services/argonaut/v0/" 
method = "GET"
resource = "Patient"
param = "id"

I tried,

val patientInfoUrl = "https://devapis.gov/services/argonaut/v0/"

        val infoInterceptor = Interceptor { chain ->
            val newUrl = chain.request().url()
                    .newBuilder()
                    .query(accountId)
                    .build()

            val newRequest = chain.request()
                    .newBuilder()
                    .url(newUrl)
                    .header("Authorization",accountInfo.tokenType + " " + accountInfo.accessToken)
                    .header("Accept", "application/json")
                    .build()

            chain.proceed(newRequest)
        }

        val infoClient = OkHttpClient().newBuilder()
                .addInterceptor(infoInterceptor)
                .build()

        val retrofit = Retrofit.Builder()
                .baseUrl(patientInfoUrl)
                .client(infoClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build()

        Logger.i(TAG, "Calling retrofit.create")
        try {
            // How to get json data here
        }catch (e: Exception){
            Logger.e(TAG, "Error", e);
        }
        Logger.i(TAG, "Finished retrofit.create")

    }

How can i get the raw json output. I don't want to implement user data class and parsing stuffs if possible. Is there any way?

Update 1

Marked duplicated post (Get raw HTTP response with Retrofit) is not for Kotlin and I need Kotlin version.

2 Answers

It is pretty easy you just need to make your network calls function like this.

@FormUrlEncoded
@POST("Your URL")
fun myNetworkCall() : Call<ResponseBody>

The point here is your network call should return a Call of type ResponseBody. And from ResponseBody you can get the response in String format.

Now when you will call this function to perform the network call you will get the raw string response.

    MyApi().myNetworkCall().enqueue(object: Callback<ResponseBody>{
        override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
            //handle error here
        }

        override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
            //your raw string response
            val stringResponse = response.body()?.string()
        }

    })

Its pretty simple. Let me know if you want any other details. Hope this helps. Thank You

You can simply use the response body of okhttp as retrofit is based on okhttp.

Here is an example which you can convert to your use case:

@GET("users/{user}/repos")
  Call<ResponseBody> getUser(@Path("user") String user);

Then you can call it like this:

Call<ResponseBody> myCall = getUser(...)
myCall.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
        // access response code with response.code()
        // access string of the response with response.body().string()
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
});

For more information see: https://stackoverflow.com/a/33286112/4428159

Related