【问题标题】:How to accept text/csv as content-type in spring-web servlet?如何在 spring-web servlet 中接受 text/csv 作为内容类型?
【发布时间】:2019-01-21 04:37:40
【问题描述】:

我想创建一个生成text/csv 内容的简单网络服务。但我不能要求它:

@RestController
public class MyServlet {
    @PostMapping(produces = {"text/csv", "application/json"})
    public Object post() {
        //...
    }
}

spring.mvc.contentnegotiation.media-types.csv=text/csv

当我以Content-Type: text/csv 作为 http 标头发送 post 请求时,我收到以下错误:

415:Content type 'text/csv' not supported

这是我的配置:

@Configuration
public class ContentNegotiationConfiguration implements WebMvcConfigurer {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer
                .favorParameter(true) //favor &format=csv
                .defaultContentType(MediaType.APPLICATION_JSON)
                .parameterName(format);
                //.mediaType("csv", new MediaType("text", "csv")) //also tried without success
    }
}

【问题讨论】:

  • 澄清一下,您想为您的用户生成一个 csv 文件吗?
  • 你试过加consumes="text/csv"吗??
  • 是消费者而不是生产者
  • 不,consumes 用于从用户那里接收到什么数据。但是我的用户没有发送任何东西,所以这里忽略了消耗。我想生成一个csv文件。
  • @mohammedkhan 这不是重复的。特别是我希望内容协商已经选择了正确的响应内容类型,如上配置。应优先使用查询参数&format=csv,因此应生成text/csv,如application.properties 中配置的那样。

标签: java spring spring-rest spring-web


【解决方案1】:

如果您(客户端)期望 csv 内容,则客户端应将 text/csv 作为 Accept 标头而不是 Content-Type 传递。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 2017-03-26
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 2014-09-17
    • 1970-01-01
    相关资源
    最近更新 更多