How to make an API request in Kotlin?

前端 未结 4 1978
悲哀的现实
悲哀的现实 2021-01-31 15:29

I am extremely new to Kotlin and APIs in general and can\'t find the syntax to create an API request using this language. I am creating a mobile version of a website so I\'m usi

4条回答
  •  太阳男子
    2021-01-31 15:46

    Once you have set your Android Studio to use Kotlin is pretty simple to do a REST call, and it's pretty much the same logic as with Java.


    Here's an example of a REST call with OkHttp:

    build.gradle

    dependencies {
        //...
        implementation 'com.squareup.okhttp3:okhttp:3.8.1'
    }
    

    AndroidManifest.xml

    
    

    MainActivity.kt

    class MainActivity : AppCompatActivity() {
    
        private val client = OkHttpClient()
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            run("https://api.github.com/users/Evin1-/repos")
        }
    
        fun run(url: String) {
            val request = Request.Builder()
                    .url(url)
                    .build()
    
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {}
                override fun onResponse(call: Call, response: Response) = println(response.body()?.string())
            })
        }
    }
    

    Below are a few more complicated examples with other libraries:

    • Network request in Kotlin with Retrofit
    • Network request in Kotlin with Retrofit and coroutines
    • Network request in Kotlin with Dagger, RxJava, Retrofit in MVP

提交回复
热议问题