【问题标题】:How to get raw json response of Retrofit in Kotlin?如何在 Kotlin 中获取 Retrofit 的原始 json 响应?
【发布时间】:2019-10-26 15:25:01
【问题描述】:

我是KotlinRetrofit 的新手。我想通过Retrofit 调用基础URL 并打印原始JSON 响应。什么是最简单的最小配置?

比方说,

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

我试过了,

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

    }

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

更新 1

标记为重复的帖子 (Get raw HTTP response with Retrofit) 不适用于 Kotlin,我需要 Kotlin 版本。

【问题讨论】:

  • 如果您只想打印响应,那么为什么不使用HttpLogIntercepter?获取原始回复Follow this ..
  • @ADM 我不知道HttpLogIntercepter
  • 看看this
  • @HemantParmar 这是在 java 中,我正在使用 Kotlin。
  • Marked duplicated post (Get raw HTTP response with Retrofit) is not for Kotlin and I need Kotlin version. 然后转换它。我喜欢你的简历中所说的“问题解决者”,而你却依赖其他人为你将 Java 代码转换为 Kotlin

标签: android rest kotlin retrofit http-get


【解决方案1】:

您只需要像这样使您的网络调用功能非常简单。

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

这里的重点是您的网络调用应该返回一个Call 类型的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()
        }

    })

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

【讨论】:

    【解决方案2】:

    你可以简单地使用 okhttp 的响应体,因为改造是基于 okhttp 的。

    这是一个您可以转换为您的用例的示例:

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

    那么你可以这样称呼它:

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

    有关详细信息,请参阅: https://stackoverflow.com/a/33286112/4428159

    【讨论】:

    • 我的问题是 Kotlin
    • getUser(...)是什么意思
    • 您可以轻松地将Java代码转换为kotlin,也可以直接在kotlin中使用java代码。
    • getUser(...) 是我在第一步中定义的接口的实现。
    • 能否请您更新您对 Kotlin 的回答。我没有得到你的 getUser。您能否也发布实施。谢谢。
    猜你喜欢
    • 2014-04-09
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    • 2017-09-24
    • 2016-11-03
    • 1970-01-01
    相关资源
    最近更新 更多