---
tags:
aliases:
date: 2024-06-05
time: 19:06:00
description:
---
Ktor是由Kotlin提供的一個framwork。
要在Android使用Ktor,需要在build.gradle加入以下的dependency:
```
implementation "io.ktor:ktor:1.2.5"
implementation "io.ktor:ktor-server-netty:1.2.5"
implementation "io.ktor:ktor-gson:1.2.5"
```
在`packagingOptions`裡,也需要加入以下的設定來必面編譯問題[[Ktor#^68d958 ]] :
```
packagingOptions {
exclude 'META-INF/*'
}
```
在`AndroidManifest.xml`中,記得加入internet的權限:
```
```
然後就是HTTP Server的code了:
```
embeddedServer(Netty, 8080) {
install(ContentNegotiation) {
gson {}
}
routing {
get("/") {
call.respond(mapOf("message" to "Hello world"))
}
}
}.start(wait=true)
```
但是這段code會block,所以需要一個thread把它包起來:
```kotlin
Thread {
httpEngine = embeddedServer(Netty, 8080) {
install(ContentNegotiation) {
gson {}
}
routing {
get("/") {
call.respond(mapOf("message" to "Hello world"))
}
get("/say/{something}") {
call.respond(mapOf("message" to "You say: " + call.parameters["something"]))
activity?.findViewById(R.id.textView)?.text = "You say: " + call.parameters["something"]
}
}
}.start(wait = false)
}.start()
```
# 參考來源
- 如果沒有這一段會產生如下錯誤 ^68d958
```
13 files found with path 'META-INF/INDEX.LIST'.
Adding a packagingOptions block may help, please refer to
https://developer.android.com/reference/tools/gradle-api/7.4/com/android/build/api/dsl/ResourcesPackagingOptions
for more information
```