【问题标题】:No HttpMessageConverter for [com.example.blog.SnapEngChatRequest] and content type [application/x-www-form-urlencoded][com.example.blog.SnapEngChatRequest] 和内容类型 [application/x-www-form-urlencoded] 没有 HttpMessageConverter
【发布时间】:2019-09-12 17:15:35
【问题描述】:

我想调用带有表单 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,但我不确定它为什么没有使用,或者我不确定我是否在这里做错了什么。我已经尝试了所有可能的方法。任何帮助都会有所帮助,谢谢!

【问题讨论】:

    标签: spring-boot kotlin resttemplate


    【解决方案1】:

    FormHttpMessageConverter 的文档中可以:

    ... 读写“application/x-www-form-urlencoded”媒体类型 作为多值映射

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

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

    【讨论】:

    • 是的,谢谢。我知道这种方式并且它正在工作,但是是否可以使用我在代码中所做的消息转换器?
    • 我引用了这个链接this
    • 不幸的是,Spring 中没有通用转换器来序列化 POJO 以形成数据。
    • 能否请您查看评论中的上述链接?
    • 内置转换器无法实现。你必须自己写。但为什么?例如,您可以在 POJO toMap 中编写一个辅助方法,它将您的对象序列化为您可以使用 RestTemplate 发送的 LinkedMultiValueMap
    猜你喜欢
    • 2021-02-03
    • 2015-04-02
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    相关资源
    最近更新 更多