1

I have this endpoint with this structure:

uri = http://127.0.0.1:9090/tables/mask

and this payload:

{
   "_id" : "5d66c9b6d5ccf30bd5b6b541",
   "connectionId" : "1967c072-b5cf-4e9e-1c92-c2b49eb771c4",
   "name" : "Customer",
   "columns" : [
       {
           "name" : "FirstName",
           "mask" : true
       },
       {
           "name" : "LastName",
           "mask" : false
       },
       {
           "name" : "City",
           "mask" : false
       },
       {
           "name" : "Phone",
           "mask" : false
       }
   ],
   "parentId" : null
} 

in my Kotlin code I have this structure to deserialize:

data class ColumnsMaskModel (val name:String, val mask:Boolean )

data class TablesMaskModel (val _id:String, val name:String, val connectionId:String, val columns:MutableList<ColumnsMaskModel?> )

and how can I use TablesMaskModel to make a HTTP post in Kotlin

1 Answer 1

1

You'll need an HTTP client to do that. Data classes themselves has nothing to do with HTTP, they are just data structures. There are a lot of HTTP clients available on Kotlin for JVM:

Let's see how to make HTTP requests in Ktor:

data class ColumnsMaskModel(val name: String, val mask: Boolean)

data class TablesMaskModel(val _id: String, val name: String, val connectionId: String, val columns: MutableList<ColumnsMaskModel?>)

fun main() = runBlocking {
    val client = HttpClient {
        install(JsonFeature) {
            serializer = JacksonSerializer()
        }
    }

    val result = client.post<String> {
        url("http://httpbin.org/post")
        contentType(ContentType.Application.Json)
        body = TablesMaskModel(
            _id = "5d66c9b6d5ccf30bd5b6b541",
            connectionId = "1967c072-b5cf-4e9e-1c92-c2b49eb771c4",
            name = "Customer",
            columns = mutableListOf(
                ColumnsMaskModel(name = "FirstName", mask = true),
                ColumnsMaskModel(name = "LastName", mask = false),
                ColumnsMaskModel(name = "City", mask = false),
                ColumnsMaskModel(name = "Phone", mask = false)
            )
        )
    }

    println(result)

    client.close()
}

Note that Ktor uses suspending functions for HTTP requests, so you'll need a coroutine scope, runBlocking in this example.

Ktor supports various "backends" for HTTP clients – Apache, Coroutines IO, curl. It also has different "features" to enable on-the-flight payloads serializations and de-serializations, like in the example above.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.