如何在Kotlin中提出API请求? [英] How to make an API request in Kotlin?
问题描述
我一般对Kotlin和API都是陌生的,无法找到使用该语言创建API请求的语法.我正在创建网站的移动版本,因此我正在使用Android Studio为已经建立的后端创建新的UI.创建请求的步骤和语法是什么?任何帮助深表感谢.
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.
推荐答案
设置您的Android Studio以使用Kotlin 进行REST调用非常简单,并且其逻辑与Java几乎相同.
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.
以下是使用 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:
- Network request in Kotlin with Retrofit
- Network request in Kotlin with Retrofit and coroutines
- Network request in Kotlin with Dagger, RxJava, Retrofit in MVP
这篇关于如何在Kotlin中提出API请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!