Where does Retrofit pull data from server?

Viewed 119

I'm learning Coroutines of Kotlin and I'm a beginner of Retrofit.

The Code A is from the artical.

It seems that Retrofit get data from local server http://localhost/, I havn't run local web server.

Where does Retrofit get data ?

Code 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
}
2 Answers

Itself!

If you look at the code: .addInterceptor(SkipNetworkInterceptor()). Interceptors process every call that is made through Retrofit.

Some people use it to log data about calls for debugging. Some people use it to automatically provide authorization tokens.

In this case, it is providing fake data.

You can read about that here:

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

You should write this IP which is the equivalent of localhost in base url.

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

But you should check your port number on localhost. After checking, you should add your port number to the part that says 3000. Replace with 3000.

Related