如何在 Kotlin 中获得 Retrofit 的原始 json 响应?

Saz*_*han 4 rest android http-get kotlin retrofit

我是Kotlin和 的新手Retrofit。我想打电话给基地URL通过Retrofit和打印的原始JSON响应。什么是最简单的最小配置?

让我们说,

base url = "https://devapis.gov/services/argonaut/v0/" 
method = "GET"
resource = "Patient"
param = "id"
Run Code Online (Sandbox Code Playgroud)

我试过,

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")

    }
Run Code Online (Sandbox Code Playgroud)

我怎样才能得到原始的 json 输出。如果可能,我不想实现用户数据类和解析内容。有什么办法吗?

更新 1

标记重复的帖子(使用 Retrofit 获取原始 HTTP 响应)不适用于 Kotlin,我需要 Kotlin 版本。

Bel*_*han 10

你只需要让你的网络调用功能像这样是很容易的。

@FormUrlEncoded
@POST("Your URL")
fun myNetworkCall() : Call<ResponseBody>
Run Code Online (Sandbox Code Playgroud)

这里的重点是您的网络调用应该返回 aCall类型ResponseBody。从ResponseBody你可以得到字符串格式的响应。

现在,当您调用此函数来执行网络调用时,您将获得原始字符串响应。

    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()
        }

    })
Run Code Online (Sandbox Code Playgroud)

它很简单。如果您想要任何其他详细信息,请告诉我。希望这可以帮助。谢谢你