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

时间:2019-04-23 13:38:36

标签: spring-boot kotlin resttemplate

我想用表单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
    )

但是不幸的是,它无法正常工作,而且我遇到了错误

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]

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

1 个答案:

答案 0 :(得分:1)

根据FormHttpMessageConverter的文档,它可以:

  

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

因此它无法从POJO中读取它。像这样发送您的数据:

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