【问题标题】:Unable to get data with RETROFIT + COROUTINE无法使用 RETROFIT + COROUTINE 获取数据
【发布时间】:2021-11-15 09:55:57
【问题描述】:

我正在尝试使用 Retrofit 进行简单的网络调用,并使用协程进行异步调用,但是当我运行应用程序时,绝对没有响应。无信息。我不知道是否正在拨打电话。请帮忙。

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import kotlinx.coroutines.*
import retrofit2.*
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET

class MainActivity : AppCompatActivity() {
    val TAG = "MainActivity"
    var job: Job? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val api = Retrofit.Builder()
            .baseUrl("https://howtodoandroid.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(RetrofitService::class.java)

        GlobalScope.launch(Dispatchers.IO) {
            val response = api.getAllMovies()
            if (response.isSuccessful) {
                val movies = response.body()
                if (movies != null) {
                    for (movie in movies) {
                        Log.d(TAG, movie.name)
                    }
                }

            }
        }

    }

}

interface RetrofitService {
    @GET("movielist.json")
    suspend fun getAllMovies() : Response<List<Movie>>
}

data class Movie(val name: String, val imageUrl: String, val category: String)

【问题讨论】:

  • 你有没有在 manifest 中添加互联网权限?
  • 你也可以发RetrofitService接口吗?你检查过日志吗?
  • 包括权限和RetrofitService,能不能也看看做请求的时候有没有日志输出?

标签: android kotlin retrofit kotlin-coroutines


【解决方案1】:

我建议你从getAllMovies() 返回Call 而不是Response,然后调用execute()

生成的代码如下所示:

interface RetrofitService {
    @GET("movielist.json")
    suspend fun getAllMovies() : Call<List<Movie>>
}

val response = api.getAllMovies().execute()

这应该可行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-17
    • 2017-06-12
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    • 2016-07-29
    • 2016-08-05
    • 2019-08-17
    相关资源
    最近更新 更多