Examples

note

Examples - 图1

This help topic is in development and will be updated in the future.

Interchanging JSON: Ktor server / Ktor client

  1. fun main(args: Array<String>) {
  2. val server = embeddedServer(
  3. Netty,
  4. port = 8080,
  5. module = Application::mymodule
  6. ).apply {
  7. start(wait = false)
  8. }
  9. runBlocking {
  10. val client = HttpClient(Apache) {
  11. install(JsonFeature) {
  12. serializer = GsonSerializer {
  13. // .GsonBuilder
  14. serializeNulls()
  15. disableHtmlEscaping()
  16. }
  17. }
  18. }
  19. val message = client.post<HelloWorld> {
  20. url("http://127.0.0.1:8080/")
  21. contentType(ContentType.Application.Json)
  22. body = HelloWorld(hello = "world")
  23. }
  24. println("CLIENT: Message from the server: $message")
  25. client.close()
  26. server.stop(1L, 1L, TimeUnit.SECONDS)
  27. }
  28. }
  29. data class HelloWorld(val hello: String)
  30. fun Application.mymodule() {
  31. install(ContentNegotiation) {
  32. gson {
  33. setPrettyPrinting()
  34. }
  35. }
  36. routing {
  37. post("/") {
  38. val message = call.receive<HelloWorld>()
  39. println("SERVER: Message from the client: $message")
  40. call.respond(HelloWorld(hello = "response"))
  41. }
  42. }
  43. }

note

Examples - 图2

You can check the ktor-samples and ktor-exercises repositories for samples and exercises.