[com.example.blog.SnapEngChatRequest] 和内容类型 [application/x-www-form-urlencoded] 没有 HttpMessageConverter

Jit*_*dra 2 resttemplate kotlin spring-boot

我想用表单 URL 编码的标头调用 post API。这是我的代码

 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
    )
Run Code Online (Sandbox Code Playgroud)

但不幸的是,它不起作用,我收到以下错误

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]
Run Code Online (Sandbox Code Playgroud)

在这里,我提供了 httpMessageConverter,但我不确定为什么它没有被接受,或者我不确定我是否在这里做错了什么。我已经尝试了一切可能。任何帮助都会有所帮助,谢谢!

Str*_*lok 7

FormHttpMessageConverter 的文档中,它可以:

...读取和写入“application/x-www-form-urlencoded”媒体类型为 MultiValueMap

所以它不能从 POJO 中读取它。像这样发送您的数据:

val data = LinkedMultiValueMap(
  mapOf("widgetId" to listOf(widgetId), "visitorMessage" to listOf("Test"))
)
Run Code Online (Sandbox Code Playgroud)