I am getting Response code 400 with the following POST connection in Kotlin using java.net
standard library shipped in Kotlin and kotlinx.serialization.json
API. The same works on a online API Testing tool, hence I suspect I am doing something wrong in sending the payload.
val con = URL("https://thirdparty-api-service.com/token").openConnection() as HttpURLConnection
con.requestMethod = "POST"
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
val myClientId : String = <my_client_id>
val myClientSecret : String = <my_client_secret>
val data = buildJsonArray {
addJsonObject {
put("grant_type", "client_credentials")
put("client_id", myClientId)
put("client_secret", myClientSecret)
}
}
Log.i(LOG_TAG,"Sending data: $data")
con.doOutput = true
con.outputStream.bufferedWriter().use {
it.write(data.toString().toCharArray())
it.flush()
}
Log.i(LOG_TAG,"Response Code: ${con.responseCode}")
con.disconnect()
The above logs the following:
Sending data: [{“grant_type”:”client_credentials”,”client_id”:”my_client_id”,”client_secret”:”my_client_secret”}]
Note that in the testing tool I used the following format for sending the payload:
grant_type=client_credentials
client_id=my_client_id
client_secret=my_client_secret