Hello, I'm trying to migrate from OkHttp to Ktor. ...
# ktor
z
Hello, I'm trying to migrate from OkHttp to Ktor. I need to split the steps into Client, Request, and Response similar to OkHttp. I tried using the following code but the results are not as expected. Headers and FormData are missing from the final request. 😥 Is there something wrong with the way I'm building the HttpRequestBuilder?
Copy code
val defaultHeaders = buildHeaders {
    append(HttpHeaders.Host, baseUrl.host)
    append(HttpHeaders.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36")
}
val request = HttpRequestBuilder().apply {
    url("$baseUrl/wap.php?action=search")
    method = <http://HttpMethod.Post|HttpMethod.Post>
    headers { appendAll(defaultHeaders) }
    formData {
        append("objectType", "2")
    }
}
val response = client.request(request)
a
The problem is that the
formData
is a function which just creates a list and doesn't mutate the request builder. To solve the problem you need to specify the request body:
Copy code
val request = HttpRequestBuilder().apply {
    url("$baseUrl/wap.php?action=search")
    method = <http://HttpMethod.Post|HttpMethod.Post>
    headers { appendAll(defaultHeaders) }
    setBody(
        MultiPartFormDataContent(
            parts = formData {
                append("objectType", "2")
            }
        )
    )
}
z
It worked, thank you!