Post requests can be made only via kotlin dsl. For post calls kohttp will set content type by rule that mentioned below.
Content type is set according to the following priority levels (higher is prioritized)
- Form or Json in body :
body() { json { ... } } ...
- Custom body type :
body(myContentType) { ... } ...
- Header :
header { "Content-type" to myContentType } ...
form
body has a application/x-www-form-urlencoded
content type
val response: Response = httpPost {
host = "postman-echo.com"
path = "/post"
param { ... }
header { ... }
body {
form { // Resulting form will not contain ' ', '\t', '\n'
"login" to "user" // login=user&
"email" to "[email protected]" // [email protected]
}
}
// or
body {
form("login=user&[email protected]")
}
}
json
body has a application/json
content type
val response: Response = httpPost {
host = "postman-echo.com"
path = "/post"
param { ... }
header { ... }
body { // Resulting json will not contain ' ', '\t', '\n'
json { // {
"login" to "user" // "login": "user",
"email" to "[email protected]" // "email": "[email protected]"
} // }
}
// or
body {
json("""{"login":"user","email":"[email protected]"}""")
}
}
In addition to form
or json
body content types it is possible to declare a custom content type.
body
DSL support three data sources: file()
, bytes()
and string()
httpPost {
body("application/json") {
string("""{"login":"user","email":"[email protected]"}""")
}
}
val imageFile = File(getResource("/cat.gif").toURI())
httpPost {
body(type = "image/gif") {
file(imageFile)
}
}
httpPost {
body { // content type is optional, null by default
bytes("string of bytes".toByteArray())
}
}
val response = httpPost {
url("http://postman-echo.com/post")
multipartBody {
+part("meta") {
json {
"token" to "$token"
}
}
+part("image") {
file(imageFile)
}
}
}