无法记录某些行

时间:2019-11-18 12:49:50

标签: android kotlin retrofit2 okhttp

我的onCreate()中的MainActivity包含以下部分代码:

    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
}

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

2 个答案:

答案 0 :(得分:1)

您可能必须在后台线程中调用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
    }
}

答案 1 :(得分:0)

尝试将“无过滤器”选项设置为