Search code examples
spring-bootkotlinresttemplate

No HttpMessageConverter for [com.example.blog.SnapEngChatRequest] and content type [application/x-www-form-urlencoded]


I wanted to call a post API with form URL encoded header. Here's my code

 var data = SnapEngChatRequest(
            widgetId = widgetId,
            visitorMessage = "Test"
    )

    val headers = HttpHeaders()

    headers.set("x-api-key", apiKey)
    headers.set("Content-Type", "application/x-www-form-urlencoded")

    val entity = HttpEntity(data, headers)

    val converter = FormHttpMessageConverter()
    converter.supportedMediaTypes = singletonList(MediaType.APPLICATION_FORM_URLENCODED)
    restTemplate.messageConverters.add(converter)

    val result = restTemplate.exchange(
            url,
            HttpMethod.POST,
            entity,
            String::class.java
    )

But unfortunately, it is not working and I'm getting below error

No HttpMessageConverter for [com.example.blog.SnapEngChatRequest] and content type [application/x-www-form-urlencoded]
org.springframework.web.client.RestClientException: No HttpMessageConverter for [com.example.blog.SnapEngChatRequest] and content type [application/x-www-form-urlencoded]

Here, I'm giving the httpMessageConverter but I'm not sure why it is not taking or I'm not sure if I'm doing something wrong here. I have tried everything possible. Any help will be helpful, Thanks!


Solution

  • From documentation for FormHttpMessageConverter it can:

    ... read and write the "application/x-www-form-urlencoded" media type as MultiValueMap

    So it can't read it from a POJO. Send your data like this:

    val data = LinkedMultiValueMap(
      mapOf("widgetId" to listOf(widgetId), "visitorMessage" to listOf("Test"))
    )