Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
100 views
in Technique[技术] by (71.8m points)

android - How to make an API request in Kotlin?

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 using Android Studio to create a new UI for an already established backend. What are the steps and syntax to creating a request? Any help is deeply appreciated.

question from:https://stackoverflow.com/questions/45219379/how-to-make-an-api-request-in-kotlin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

<uses-permission android:name="android.permission.INTERNET" />

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...