【问题标题】:How to get full URL that Retrofit uses for API calls?如何获取 Retrofit 用于 API 调用的完整 URL?
【发布时间】:2022-01-24 21:38:21
【问题描述】:

我需要尝试获取用于进行 API 调用的完整 URL。

例如:

@GET("recipes/hot/")
suspend fun doCall(): Recipes

我想以某种方式获取此 API 调用正在执行的完整 URL(基本 url + 路径等)。

我找到的一个解决方案是:

@GET("recipes/hot/")
suspend fun doCall(): Response<Recipes>

然后你可以从这个响应包装类中获取url

但是,代码库中的其余 api 调用并没有用Response 包装返回类型,所以我真的想避免这样做。

是否有一些简单的方法可以从 Retrofit api 调用中获取完整的 URL?

【问题讨论】:

标签: android retrofit retrofit2


【解决方案1】:

您需要为调试模式添加拦截器日志记录,这将在 Android Studio logcat 中为您提供日志,同时 API 命中并返回响应。 下面是一个例子,根据你的需要重构它。

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
OkHttpClient.Builder httpclient = new OkHttpClient.Builder();
httpclient.addInterceptor(logging);

if (BuildConfig.DEBUG) {
            // development build
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        } else {
            // production build
            logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
        }

   Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(WebServiceConstants.SERVER_URL)
                .client(httpclient.build())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

【讨论】:

  • 出于调试目的,我不需要记录调用。但只要进行 API 调用,我只需要将完整的 URL 传递给另一个函数调用。 HttpLoggingInterceptor 会对此有所帮助,还是仅将信息输出到 logcat 中?
  • 是的,你可以从日志中获取完整的 api url。仅用于调试意味着它会在开发而不是发布时为您提供帮助。
猜你喜欢
  • 1970-01-01
  • 2011-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多