【问题标题】:Where does Retrofit pull data from server?Retrofit 在哪里从服务器中提取数据?
【发布时间】:2020-07-12 17:51:45
【问题描述】:

我正在学习 Kotlin 的 Coroutines,我是 Retrofit 的初学者。

代码 A 来自artical

似乎Retrofit 从本地服务器http://localhost/ 获取数据,我没有运行本地Web 服务器。

Retrofit 从哪里获取数据?

代码 A

private val service: MainNetwork by lazy {
    val okHttpClient = OkHttpClient.Builder()
            .addInterceptor(SkipNetworkInterceptor())
            .build()

    val retrofit = Retrofit.Builder()
            .baseUrl("http://localhost/")
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()

    retrofit.create(MainNetwork::class.java)
}

fun getNetworkService() = service

/**
 * Main network interface which will fetch a new welcome title for us
 */
interface MainNetwork {
    @GET("next_title.json")
    suspend fun fetchNextTitle(): String
}

【问题讨论】:

    标签: android kotlin retrofit


    【解决方案1】:

    本身!

    如果您查看代码:.addInterceptor(SkipNetworkInterceptor())。拦截器处理通过 Retrofit 进行的每个调用。

    有些人使用它来记录有关调试调用的数据。有些人使用它来自动提供授权令牌。

    在这种情况下,它提供了虚假数据。

    你可以在这里阅读:

    https://github.com/googlecodelabs/kotlin-coroutines/blob/master/coroutines-codelab/finished_code/src/main/java/com/example/android/kotlincoroutines/util/SkipNetworkInterceptor.kt

    【讨论】:

      【解决方案2】:

      你应该在基本 url 中写下这个相当于 localhost 的 IP。

      val retrofit = Retrofit.Builder()
              .baseUrl("http://10.0.2.2:3000/")
              .client(okHttpClient)
              .addConverterFactory(GsonConverterFactory.create())
              .build()
      

      但是你应该在 localhost 上检查你的端口号。检查后,您应该将端口号添加到显示 3000 的部分。替换为 3000。

      【讨论】:

        猜你喜欢
        • 2017-06-12
        • 2018-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-20
        • 2014-09-23
        相关资源
        最近更新 更多