vault backup: 2024-06-06 14:24:32
This commit is contained in:
@@ -9,9 +9,13 @@ description:
|
|||||||
Ktor是由Kotlin提供的一個framwork。
|
Ktor是由Kotlin提供的一個framwork。
|
||||||
要在Android使用Ktor,需要在build.gradle加入以下的dependency:
|
要在Android使用Ktor,需要在build.gradle加入以下的dependency:
|
||||||
```
|
```
|
||||||
implementation "io.ktor:ktor:1.2.5"
|
implementation "io.ktor:ktor-server-core:2.0.1" // Ktor的核心包
|
||||||
implementation "io.ktor:ktor-server-netty:1.2.5"
|
implementation "io.ktor:ktor-server-jetty:2.0.1" // 供Ktor使用的引擎包,另外有Jetty, Tomcat, CIO可用
|
||||||
implementation "io.ktor:ktor-gson:1.2.5"
|
implementation "io.ktor:ktor-gson:1.2.5"
|
||||||
|
// implementation "io.ktor:ktor-server-call-logging:2.0.1" // 用於印出Request及Response的log用
|
||||||
|
// implementation "io.ktor:ktor-server-partial-content:2.0.1" // 用於支援PartialContent用
|
||||||
|
// implementation "io.ktor:ktor-server-cors:2.0.1" // 用於支援CORS用
|
||||||
|
// implementation "io.ktor:ktor-server-html-builder:2.0.1" // 用於回傳客製html用
|
||||||
```
|
```
|
||||||
|
|
||||||
在`packagingOptions`裡,也需要加入以下的設定來必面編譯問題[[Ktor#^68d958 ]] :
|
在`packagingOptions`裡,也需要加入以下的設定來必面編譯問題[[Ktor#^68d958 ]] :
|
||||||
@@ -26,18 +30,22 @@ packagingOptions {
|
|||||||
<uses-permission android:name="android.permission.INTERNET"/>
|
<uses-permission android:name="android.permission.INTERNET"/>
|
||||||
```
|
```
|
||||||
|
|
||||||
然後就是HTTP Server的code了:
|
然後就是 HTTP Server 的 code 了,注意 Netty 在 Android 上不能用,要改用 Jetty 或是 CIO:
|
||||||
```
|
```kotlin
|
||||||
embeddedServer(Netty, 8080) {
|
import io.ktor.server.jetty.Jetty
|
||||||
install(ContentNegotiation) {
|
import io.ktor.server.engine.embeddedServer
|
||||||
gson {}
|
import io.ktor.server.routing.routing
|
||||||
|
import io.ktor.server.routing.get
|
||||||
|
import io.ktor.server.application.*
|
||||||
|
import io.ktor.server.response.respondText
|
||||||
|
|
||||||
|
embeddedServer(Jetty, 9000) {
|
||||||
|
routing {
|
||||||
|
get("/") {
|
||||||
|
call.respondText("Hello, world!")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
routing {
|
}.start(wait = false)
|
||||||
get("/") {
|
|
||||||
call.respond(mapOf("message" to "Hello world"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}.start(wait=true)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
但是這段code會block,所以需要一個thread把它包起來:
|
但是這段code會block,所以需要一個thread把它包起來:
|
||||||
|
|||||||
Reference in New Issue
Block a user