androidkotlin-multiplatformktor

how can i excute this cURL with Ktor Client For Kotlin-multiplatform?


curl -X POST
-H "X-Parse-Application-Id: ehUKQVObBspFk0MBFNSSg3MwLJofpeoFtDhQNIgS"
-H "X-Parse-REST-API-Key: 9HNNfwY6ITbUGqsfMSJS3OlQVqYfm5EAiZWVe012"
-H "Content-Type: application/json"
-d "{ "file_type":"A string","encryption_tool_id":"A string","user_id":"A string","query":"A string" }"
https://encyriptionapp.b4a.io/classes/UserFiles


Solution

  • val client = HttpClient(Apache) {}
    
    client.post<String>("https://encyriptionapp.b4a.io/classes/UserFiles") {
        headers.append("X-Parse-Application-Id", "ehUKQVObBspFk0MBFNSSg3MwLJofpeoFtDhQNIgS")
        headers.append("X-Parse-REST-API-Key", "9HNNfwY6ITbUGqsfMSJS3OlQVqYfm5EAiZWVe012")
        contentType(ContentType.Application.Json)
        body = """
            { "file_type":"A string","encryption_tool_id":"A string","user_id":"A string","query":"A string" }
        """.trimIndent()
    }
    

    Also, you can use the JsonFeature for serializing objects to JSON.

    Here is a code generated by my tool c2k for Ktor 3.*:

    import io.ktor.client.HttpClient
    import io.ktor.client.request.post
    import io.ktor.client.request.setBody
    import io.ktor.client.statement.bodyAsText
    import kotlinx.coroutines.runBlocking
    
    fun main() = runBlocking {
        val client = HttpClient {
            followRedirects = false
        }
        val response = client.post("https://encyriptionapp.b4a.io/classes/UserFiles") {
            headers.append("X-Parse-Application-Id", "ehUKQVObBspFk0MBFNSSg3MwLJofpeoFtDhQNIgS")
            headers.append("X-Parse-REST-API-Key", "9HNNfwY6ITbUGqsfMSJS3OlQVqYfm5EAiZWVe012")
            headers.append("Content-Type", "application/json")
    
            setBody("{ \"file_type\":\"A string\",\"encryption_tool_id\":\"A string\",\"user_id\":\"A string\",\"query\":\"A string\" }")
        }
        print(response.bodyAsText())
    }