【发布时间】: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