9

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.

Community
  • 1
  • 1
Sazzad Hissain Khan
  • 37,929
  • 33
  • 189
  • 256
  • If you only want to print the response then why not use `HttpLogIntercepter`? To Get raw response [Follow this](https://stackoverflow.com/questions/33282889/get-raw-http-response-with-retrofit) .. – ADM Jun 12 '19 at 07:27
  • @ADM I did not know about `HttpLogIntercepter`. – Sazzad Hissain Khan Jun 12 '19 at 07:28
  • Have look [this](https://stackoverflow.com/a/33256827/5110595) – Hemant Parmar Jun 12 '19 at 07:30
  • 1
    @HemantParmar This is in java and I am working on Kotlin. – Sazzad Hissain Khan Jun 12 '19 at 07:38
  • You can convert it. – Hemant Parmar Jun 12 '19 at 07:46
  • @SazzadHissainKhan Here is a Doc illustrating about logging with a one liner code .. https://futurestud.io/tutorials/retrofit-2-log-requests-and-responses.. If you are having problem with Kotlin Syntax then you can write it in java and later covert it in Kotlin then Understand the syntax .. – ADM Jun 12 '19 at 07:51
  • 4
    `Marked duplicated post (Get raw HTTP response with Retrofit) is not for Kotlin and I need Kotlin version.` then convert it. I like how your bio says "problem solver" yet you rely on others to convert Java code to Kotlin **for you** – Zun Jun 12 '19 at 08:13
  • Possible duplicate of [Get raw HTTP response with Retrofit](https://stackoverflow.com/questions/33282889/get-raw-http-response-with-retrofit) – denvercoder9 Jun 18 '19 at 06:34
  • @rafid059 please read my post carefully until the end. – Sazzad Hissain Khan Jun 18 '19 at 07:05

2 Answers2

21

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

Belal Khan
  • 2,099
  • 2
  • 22
  • 32
2

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

Umar Hussain
  • 3,461
  • 1
  • 16
  • 38