0

I am trying to access the DVLA's Vehicle Enquiry API. Ive got this working with a really simple example in Python, but I really want to get this working in Kotlin using OKHttp so i can use the code in an Android app.

There seems to be some issue i cant figure out with the FormBody.Builder() and the vehicle registration that i put in the body. The error im getting from the API is...

{"errors":[{"status":"400","code":"ENQ108","detail":"Invalid format for field - vehicle registration number","title":"Bad Request"}]}

The DVLA's website shows a cUrl request example, I converted that to Python and it works perfectly, but i cant figure out what im missing when doing it with OKHttp/Kotlin.

You'll see in the Kotlin code i added a println(request) just so i could see what was being sent to the api. that request when printed contains the url + header, but NO body!

enter image description here

Kotlin Code - not working

import okhttp3.*
import java.io.IOException

private val client = OkHttpClient()

private val url_dvla = "https://driver-vehicle-licensing.api.gov.uk/vehicle-enquiry/v1/vehicles"
private val auth_dvla = "MY_API_KEY"

fun main(){
    run(url_dvla)
}

fun run(url: String){
    val requestBody = FormBody.Builder()
        .add("registrationNumber", "AP08EKT")
        .build()
    
    val request = Request.Builder()
        .url(url)
        .post(requestBody)
        .addHeader("x-api-key", auth_dvla)
        .build()

    println(request)

    client.newCall(request).enqueue(object : Callback{
        override fun onFailure(call: Call, e: IOException) {
            TODO("Not yet implemented")
        }

        override fun onResponse(call: Call, response: Response) {
            println(response.body?.string())
        }
    })
}
arnzzz
  • 61
  • 5
  • I don't think [`Request.toString()`](https://github.com/square/okhttp/blob/3437eb759ad13f18bcede893992fb2af567fbbc6/okhttp/src/jvmMain/kotlin/okhttp3/Request.kt#L157-L179) will print the body. – aSemy Dec 03 '22 at 11:19
  • hey @aSemy. Yeah i just noticed that, when i print request.body it actually does show me the body. So the main problem is WHY am i still getting a response that it is a bad request? am i not using the FormBody.Builder() correctly? – arnzzz Dec 03 '22 at 11:25
  • I suspect the media headers are missing. Try creating a JSON object, and not using form builder. https://stackoverflow.com/questions/34179922/okhttp-post-body-as-json – aSemy Dec 03 '22 at 11:31
  • thanks @aSemy. the bottom answer actually worked for me :) https://stackoverflow.com/a/60110536/2124780 – arnzzz Dec 03 '22 at 11:39

0 Answers0