android - 无法记录某些行

标签 android kotlin retrofit2 okhttp

我的MainActivityonCreate()包含这部分代码:

    val weatherService = RetrofitFactory.retrofit(AppConstants.OWM_API_URL)
        .create(OwmApi::class.java)
    GlobalScope.launch(Dispatchers.Main) {
        val request = weatherService.getCurrentWeatherDataByName("Bengaluru", "metric")
        Log.i("Response 0", 0.toString())
        try {
            val response = request.await()
            if(response.isSuccessful) {
                Log.i("Response 2", 2.toString())
                val weatherResponse = response.body()
                Log.i("Response 3", 3.toString())
                Log.i("Response", weatherResponse.toString())
                println(weatherResponse)
            }
            else {
                Log.i("Response 5", 5.toString())
                Log.d(TAG, response.errorBody().toString())
            }
        }
        catch (e: Exception) {
            e.stackTrace
        }
    }

weatherService的客户端包含一个拦截器,其定义如下:

private val loggingInterceptor =  HttpLoggingInterceptor().apply {
    level = HttpLoggingInterceptor.Level.BODY
}

现在,当我运行我的应用程序时,我只看到带有 Response 0 标记的日志,但看不到 Response,甚至在我更改时看不到代码的 else 部分查询参数为无效值。也许这与 loggingInterceptor 有关,但我仍然不确定为什么尽管 response.isSuccessful 部分为真,但某些日志消息没有出现。

最佳答案

你必须在后台线程中调用你的 api 调用,可能会出现异常。

所以像下面这样尝试

 val weatherService = RetrofitFactory.retrofit(AppConstants.OWM_API_URL)
    .create(OwmApi::class.java)
GlobalScope.launch(Dispatchers.IO) {
    val request = weatherService.getCurrentWeatherDataByName("Bengaluru", "metric")
    Log.i("Response 0", 0.toString())
    try {
        val response = request.await()
        if(response.isSuccessful) {
            Log.i("Response 2", 2.toString())
            val weatherResponse = response.body()
            Log.i("Response 3", 3.toString())
            Log.i("Response", weatherResponse.toString())
            println(weatherResponse)
        }
        else {
            Log.i("Response 5", 5.toString())
            Log.d(TAG, response.errorBody().toString())
        }
    }
    catch (e: Exception) {
        e.stackTrace
    }
}

关于android - 无法记录某些行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58914950/

相关文章:

android - 在模拟器上使用 c2dm 获取注册 ID

android - Kotlin 1.4.20 - 构建速度较慢

android - Firebase 通知未在前台显示

android PPM编码器音频库

android - PhoneGap cordova 创建卡住

java - 为什么不能从Android应用程序向MySQL插入数据

android - 将标签设置为翻新调用,以便稍后通过标签取消

java - 如何使用 Kotlin 和 jackson ObjectMapper 从 json 中删除属性

java - 改造具有空字段的获取对象

Android Retrofit 2 简单 XML 转换器