1

I want to make post request with Ktor but I get Error 400.

the curl looks like this :

curl --location --request POST 'https://api.jdoodle.com/execute' \
--header 'Content-Type: application/json' \
--data-raw '{
   "script" : "console.log('\''hello'\'')",
   "language": "nodejs",
   "versionIndex": "1",
   "clientId": "....",
   "clientSecret": "...."
}'

Here is my code :

val client = HttpClient {
        install(JsonFeature) {
            val json = Json {
                isLenient = true
                ignoreUnknownKeys = true
            }
            serializer = KotlinxSerializer(json)
        }
    }

fun fetchData(requestBody: Request): Response {
        return client.post(BASE_URL){
            contentType(ContentType.Application.Json)
            body = requestBody
        }
    }

@Serializable
data class Request(....)

What am I doing wrong ?

zzz
  • 83
  • 1
  • 9
  • What's in requestBody ? – Hassan May 13 '22 at 19:10
  • @Hassan Request( val script: String="fun main(args: Array) { print(\"ndfdfdf\")}", val language: String = "kotlin", val versionIndex :String = "1", val clientId :String = "...", val clientSecret :String = ".." ) – zzz May 13 '22 at 19:16
  • 2
    Try to log `Json.encodeToString(requestBody)` to see wether it's the string you expect to send, or just add `install(Logging) { level = LogLevel.ALL }` for your client. If you have any default values of your `request`, you need to set `encodeDefaults = true`, as by default these are not gonna be encoded. – Phil Dukhov May 14 '22 at 02:56
  • @Pylyp Dukhov Adding encodeDefaults = true helped thank you so much ! – zzz May 14 '22 at 08:35

0 Answers0