首页 > 解决方案 > 如何记录,我正在访问的 URL 改造

问题描述

我正在使用改造与 BE 通信,我想记录我正在点击的 URL、我正在发送的正文以及我得到的响应(如 401、404)。

这是为了知道我是否点击了正确的 url 标题、正文和实际 URL 是什么,以验证我正在发送所需的所有正确信息

我实现了 HttpLoggingInterceptor 但没有记录它,或者我以正确的方式记录它

你能建议吗?

object RetrofitBuilder {
    private const val BASE_URL = "https://xxxx.xxxxxx.com/"

    private fun getRetrofit(): Retrofit {
        var interceptor: HttpLoggingInterceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        val client = OkHttpClient.Builder().addInterceptor(interceptor).build()

        return Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build() //Doesn't require the adapter
    }

    val apiService: ApiService = getRetrofit().create(ApiService::class.java)
}

应用服务

@POST
    suspend fun postData(@Url url: String, @Body Data: Data, @Header("Autzn") authHeader: String)

ApiHelper

//注意:这里我使用不同的 URL,但不是顶部定义的 baseUrl

apiService.postData("https://abcd.com/msg/oauth2/123456", Data,
            "token")

//Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.6.0'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.2.1'

请建议如何记录网址信息

谢谢R

标签: androidkotlinloggingretrofit

解决方案


这就是我在日志中记录 url 的方式

val retrofitApi: RetrofitInterface
        get() {
            if (retrofitInterface == null) {
                val logger = HttpLoggingInterceptor()
                logger.level = HttpLoggingInterceptor.Level.BODY
                val okHttpClient = OkHttpClient.Builder()
                        .connectTimeout(30, TimeUnit.SECONDS)
                        .writeTimeout(30, TimeUnit.SECONDS)
                        .readTimeout(30, TimeUnit.SECONDS)
                        .addInterceptor(logger).build()


                val retrofit = Retrofit.Builder()
                        .baseUrl(REST_HOST)
                        .addConverterFactory(GsonConverterFactory.create(GsonBuilder()
                                .setLenient()
                                .create()))
                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .client(okHttpClient)
                        .build()
                retrofitInterface = retrofit.create(RetrofitInterface::class.java)
            }
            return this.retrofitInterface!!
        }

推荐阅读