HTTP Client Examples
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. }
10. runBlocking {
11. val client = HttpClient(Apache) {
12. install(JsonFeature) {
13. serializer = GsonSerializer {
14. // .GsonBuilder
15. serializeNulls()
16. disableHtmlEscaping()
17. }
18. }
19. }
21. val message = client.post<HelloWorld> {
22. url("http://127.0.0.1:8080/")
23. contentType(ContentType.Application.Json)
24. body = HelloWorld(hello = "world")
25. }
27. println("CLIENT: Message from the server: $message")
29. client.close()
30. server.stop(1L, 1L, TimeUnit.SECONDS)
31. }
32. }
34. data class HelloWorld(val hello: String)
36. fun Application.mymodule() {
37. install(ContentNegotiation) {
38. gson {
39. setPrettyPrinting()
40. }
41. }
42. routing {
43. post("/") {
44. val message = call.receive<HelloWorld>()
45. println("SERVER: Message from the client: $message")
46. call.respond(HelloWorld(hello = "response"))
47. }
48. }
49. }
You can check the ktor-samples and ktor-exercises repositories for samples and exercises.
