https://kotlinlang.org logo
#ktor
Title
e

ESchouten

06/07/2023, 6:28 PM
Hi Ktorians! With Ktor client I do the following request:
Copy code
<http://client.post|client.post>(loginUrl) {
    setBody(FormDataContent(Parameters.build {
        append("username", username)
        append("password", password)
        append("submit", "Log in")
    }))
}
This results in a successful login. Now with Javascript I want to do the same:
Copy code
fetch(loginUrl, {
    method: 'POST',
    headers:{
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: new URLSearchParams({
        username,
        password,
        submit: 'Log in'
    })
 })
This does not result in a successful login. Can anybody tell me how Ktor client handles this Form post different than JS does?
a

Aleksei Tirman [JB]

06/08/2023, 9:54 AM
I suggest making both requests and observe the difference using the WireShark or a similar tool.
e

ESchouten

06/08/2023, 1:45 PM
It ended up being that KTOR sends the form as binary data, and fetch does not support binary formats in its requests. The following works with a nodejs https request:
Copy code
import https from 'https'

const options = {
   host,
   path,
   method: 'POST',
   headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
   }
}

const request = https.request(options)
request.write(Buffer.from(btoa(params.toString()), 'base64'))
request.end();
1